Point picker event_handler drawing line and displaying coordinates in matplotlib

懵懂的女人 提交于 2019-12-02 08:19:59

You can use the 'button_press_event' to connect to a method, which verifies that the click has happened close enough to the yaxis spine and then draws a horizontal line using the clicked coordinate.

import matplotlib.pyplot as plt

class PointPicker(object):
    def __init__(self, ax, clicklim=0.05):
        self.fig=ax.figure
        self.ax = ax
        self.clicklim = clicklim
        self.horizontal_line = ax.axhline(y=.5, color='y', alpha=0.5)
        self.text = ax.text(0,0.5, "")
        print self.horizontal_line
        self.fig.canvas.mpl_connect('button_press_event', self.onclick)


    def onclick(self, event):
        if event.inaxes == self.ax:
            x = event.xdata
            y = event.ydata
            xlim0, xlim1 = ax.get_xlim()
            if x <= xlim0+(xlim1-xlim0)*self.clicklim:
                self.horizontal_line.set_ydata(y)
                self.text.set_text(str(y))
                self.text.set_position((xlim0, y))
                self.fig.canvas.draw()


if __name__ == '__main__':

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.bar([0,2,3,5],[4,5,1,3], color="#dddddd")
    p = PointPicker(ax)
    plt.show()

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