2017-05-14 44 views
0

我需要在鼠標單擊後刷新matplotlib欄圖。該圖應取event.ydata值並根據它重新繪製數據。我能夠從鼠標事件中檢索這個值,但是當我嘗試刷新這個圖時,似乎沒有任何事情發生。這裏是我的代碼:鼠標單擊事件後刷新繪圖

#df is a pd.DataFrame, I have to plot just the df_mean with error bars (marginOfError) 
df_mean = df.mean(axis=1) 
df_std = df.std(axis=1) 
marginOfError = 1.96*df_std/np.sqrt(3650) 

index = np.arange(4) 

def print_data(threshold):  
    colors = [] 

    for i,err in zip(df_mean,marginOfError): 
     if(i + err < threshold): 
      colors.append('#001f7c') 
     elif(i - err > threshold): 
      colors.append('#bc0917') 
     else: 
      colors.append('#e0d5d6') 

    fig, ax = plt.subplots() 

    plt.bar(index, df_mean, 0.85, 
        alpha=0.85, 
        color=colors, 
        yerr=marginOfError) 

    plt.xticks(index, df.index) 

    #horizontal threshold line 
    ax.plot([-0.5, 3.5], [threshold, threshold], "c-") 

# first print data with a given threshold value 
print_data(df_mean.iloc[1]) 

def onclick(event): 
    plt.gca().set_title('{}'.format(event.ydata)) 
    print_data(event.ydata)  

plt.gcf().canvas.mpl_connect('button_press_event', onclick) 
fig.canvas.draw() 

我在做什麼錯?

回答

1

您可能想在同一圖中繪製每個新圖。因此,您應該在重複調用的函數之外創建圖形和座標軸。因此,將fig, ax = plt.subplots()放在該函數的外部,並且在繪製新的繪圖之前,您可以清除軸,ax.clear()

最後,實際上你需要通過把

plt.gcf().canvas.draw_idle() 

onclick函數結束時重繪的畫布。

+0

謝謝,這完美的作品! –