Dynamically adding a vertical line to matplotlib plot

可紊 提交于 2021-02-16 08:56:45

问题


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:


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


来源:https://stackoverflow.com/questions/13124088/dynamically-adding-a-vertical-line-to-matplotlib-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!