1

I am trying to use the mouse to plot points on an image. The problem: the image appears, but when I click on the mouse, nothing is plotted (even if I click several times).

My version of Python is Python 2.7, with Anaconda and the IPython console. I type %pylab in the Ipython console before running the script.

Here is my code:

import numpy as np
from matplotlib import pyplot as plt 
#Some code here [. . .]

fig, ax = plt.subplots(1)
ax.imshow(img, interpolation = 'bicubic')
'''preventing plot from rescaling image:'''
ax.set_xlim([0.0, img.shape[1]])
ax.set_ylim([img.shape[0], 0.0])
ax.hold(True)
ax.autoscale = False
#ax.plot(100,100, 'ro')  # This works

class MouseMonitor:
    flag = True
    x = 0.
    y = 0.  
    fig = None
    axes = None

    def __init__(self, fig, ax):
        self.axes = ax
        self.fig = fig
    def __call__(self, event):
        if self.flag:
            print('({}, {})'.format(event.xdata, event.ydata))
            self.flag = False
        else:
            d = np.linalg.norm([event.xdata - self.x, event.ydata - self.y])
            print('({}, {})\n\n distance between points: {} m\n\n-------------------\n'.format(event.xdata, event.ydata, d))
            self.flag = True                       
        self.x = event.xdata
        self.y = event.ydata
        self.axes.plot(self.y, self.x, 'ro', linewidth = 5) #This don't work

mouse = MouseMonitor(fig, ax)

cid = fig.canvas.mpl_connect('button_press_event', mouse) 
4
  • 1
    You need to add a self.axes.figure.canvas.draw_idle() call into the callback to till the canvas to redraw. The OO methods are lazy to avoid un-needed redraws. Commented Oct 27, 2015 at 14:52
  • self.fig.canvas.draw_idle() will also work, didn't see you captured both. Commented Oct 27, 2015 at 14:52
  • Thank you so many tcaswell. It works fine. Commented Oct 27, 2015 at 14:57
  • You should answer your own question with that information. Commented Oct 27, 2015 at 15:03

1 Answer 1

1

Answer from tcaswell comment:

Add a self.axes.figure.canvas.draw_idle() call into the callback.

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.