8

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 1

18

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()
Sign up to request clarification or add additional context in comments.

4 Comments

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..
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.
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
I changed plt.plot() by ax.scatter() without the ',' and it works for me in Spyder

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.