Reputation: 681
I need to refresh a matplotlib bar plot after a mouse click. The plot should take the event.ydata value and replot data according to it. I was able to retrieve this value from the mouse event, but when I try to refresh the plot nothing seems to happen. Here is my code:
#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()
What am I doing wrong?
Upvotes: 3
Views: 2519
Reputation: 339220
You would probably want to plot each new plot in the same figure. Therefore you should create the figure and axes outside the repetitively called function. Thus put fig, ax = plt.subplots()
outside the function, and inside you may clear the axes, ax.clear()
before drawing a new plot to it.
At the end, you need to actually redraw the canvas by putting
plt.gcf().canvas.draw_idle()
at the end of the onclick
function.
Upvotes: 5