动态地将垂直线添加到matplotlib图中



当用户单击特定点时,我正在尝试将垂直线添加到matplotlib图。

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

这是一个(几乎)工作的例子。当我单击一个点时,确实调用了onpick方法,并且数据似乎是正确的,但是没有显示垂直线。我需要做什么才能使垂直线出现?

谢谢

您需要更新画布图(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()

最新更新