Reputation: 307
I'm trying to update a matplotlib plot with a new data point when a user clicks on the graph. How can I achieve this? I've tried using things like plt.draw() without any success. Here's my attempt so far. I feel I'm missing something fundamental here.
x=[1]
y=[1]
def onclick(event):
if event.button == 1:
x.append(event.xdata)
y.append(event.ydata)
fig,ax=plt.subplots()
ax.scatter(x,y)
fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()
plt.draw()
Upvotes: 6
Views: 10784
Reputation: 1667
There's nothing wrong with the way you bind your event. However, you only updated the data set and did not tell matplotlib
to do a re-plot with new data. To this end, I added the last 4 lines in the onclick
method. They are self-explanatory, but there are also comments.
import matplotlib.pyplot as plt
x = [1];
y = [1];
def onclick(event):
if event.button == 1:
x.append(event.xdata)
y.append(event.ydata)
#clear frame
plt.clf()
plt.scatter(x,y); #inform matplotlib of the new data
plt.draw() #redraw
fig,ax=plt.subplots()
ax.scatter(x,y)
fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()
plt.draw()
NOTE: matplotlib
in my computer (ubuntu 14.04) changes the scale, so you probably want to look into how to fix the x-y scale.
Upvotes: 13