3

I'm trying to add vertical lines to a matplotlib plot dynmically when a user clicks on a particular point.

import matplotlib.pyplot as plt
import matplotlib.dates as mdate


class PointPicker(object):
    def __init__(self,dates,values):

        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        self.lines2d, = self.ax.plot_date(dates, values, linestyle='-',picker=5)

        self.fig.canvas.mpl_connect('pick_event', self.onpick)
        self.fig.canvas.mpl_connect('key_press_event', self.onpress)

    def onpress(self, event):
        """define some key press events"""
        if event.key.lower() == 'q':
            sys.exit()

    def onpick(self,event):
        x = event.mouseevent.xdata
        y = event.mouseevent.ydata
        print self.ax.axvline(x=x, visible=True)
        x = mdate.num2date(x)
        print x,y,type(x)


if __name__ == '__main__':
    import numpy as np
    import datetime

    dates=[datetime.datetime.now()+i*datetime.timedelta(days=1) for i in range(100)]
    values = np.random.random(100)

    plt.ion()
    p = PointPicker(dates,values)
    plt.show()

Here's an (almost) working example. When I click a point, the onpick method is indeed called and the data seems to be correct, but no vertical line shows up. What do I need to do to get the vertical line to show up?

Thanks

1 Answer 1

5

You need to update the canvas drawing (self.fig.canvas.draw()):

def onpick(self,event):
    x = event.mouseevent.xdata
    y = event.mouseevent.ydata
    L =  self.ax.axvline(x=x)
    self.fig.canvas.draw()
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think you need the add_line, just the draw

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.