Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Matplotlib plot when clicked

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()
like image 604
Collaptic Avatar asked Sep 03 '26 10:09

Collaptic


1 Answers

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.

like image 188
TuanDT Avatar answered Sep 04 '26 23:09

TuanDT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!