6

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()

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.