Point picker event_handler drawing line and displaying coordinates in matplotlib

后端 未结 1 501
野性不改
野性不改 2021-01-26 08:18

I have the following class that draws a vertical line through the y-axis, so that when I click on it a horizontal line gets drawn at the location. My goal is to get the y-coordi

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-26 09:00

    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="#ffffdffffd")
        p = PointPicker(ax)
        plt.show()
    

    0 讨论(0)
提交回复
热议问题