mgilson
mgilson

Reputation: 309841

Dynamically adding a vertical line to matplotlib plot

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

Upvotes: 3

Views: 5786

Answers (1)

mgilson
mgilson

Reputation: 309841

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()

Upvotes: 5

Related Questions