鼠标单击事件后刷新绘图

Dav*_*ino 3 python matplotlib event-handling bar-chart

我需要在单击鼠标后刷新 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()
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Imp*_*est 5

您可能希望在同一个图中绘制每个新图。因此,您应该在重复调用的函数之外创建图形和轴。因此,将其放在fig, ax = plt.subplots()函数外部,在内部ax.clear()绘制新图之前,您可以清除轴。

最后,您需要通过放置来实际重新绘制画布

plt.gcf().canvas.draw_idle()
Run Code Online (Sandbox Code Playgroud)

在函数的末尾onclick