How is it possible to plot a dot/circle at the point being clicked on in matplotlib(python 3)? Moreover i want to read the pixel value of each dot. I have tried plotting the circles but each time i read a different coordinate value, the previous circle is overwritten by the new circle. thank you
1 Answer
You have to register an onclick event with the figure. Below is an example that plots a dot where the user clicks:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])
def onclick(event):
print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
(event.button, event.x, event.y, event.xdata, event.ydata))
plt.plot(event.xdata, event.ydata, ',')
fig.canvas.draw()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
4 Comments
Kai
wow, thank you very much. Almost an hour of Googling and nothing worked in an Jupyter notebook except this example. I don't get the print though, not sure where Jupyter sends it... don't see it on terminal..
Kai
Only difference between what I was doing and this code is that I was trying to draw a point at event.x,event.y instead of event.xdata,event.ydata.. very confusing actually.
Ken Grimes
Thanks for the code, but I have a problem running it on spyder, namely the plot reacts by printing 'button=... etc' but the point is not plotted, the plot stays empty the whole time
Ken Grimes
I changed plt.plot() by ax.scatter() without the ',' and it works for me in Spyder