动态地向matplotlib图添加一条垂直线 [英] Dynamically adding a vertical line to matplotlib plot

查看:49
本文介绍了动态地向matplotlib图添加一条垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击特定点时,我试图动态地向matplotlib图添加垂直线.

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

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

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?

谢谢

推荐答案

您需要更新画布绘图(self.fig.canvas.draw()):

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

这篇关于动态地向matplotlib图添加一条垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆