2017-03-18 49 views
0

我有以下类绘制通过Y轴的垂直线,以便当我点击它时在该位置绘制水平线。 我的目标是让y坐标实际打印在水平线绘制的y轴上。对于测试,我试图用y-ccordinate打印标题,但它不能按预期工作。点拾取器event_handler绘制线并显示matplotlib中的坐标

我想要真正实现的是让条形图上的y轴可点击,以便用户可以在y轴上选择一个点,然后发生一堆“东西”(包括绘图水平线)。我真的没有办法做到这一点,除了在y轴上绘制一条可绘制的垂直线以使其可以被选择。这似乎相当杂乱,但我还没有任何其他方法取得任何成功。

import matplotlib.pyplot as plt 

class PointPicker(object): 
    def __init__(self): 

     self.fig = plt.figure() 
     self.ax = self.fig.add_subplot(111) 
     self.lines2d, = self.ax.plot((0, 0), (-6000, 10000), 'k-', linestyle='-',picker=5) 

     self.fig.canvas.mpl_connect('pick_event', self.onpick) 
     self.fig.canvas.mpl_connect('key_press_event', self.onpress) 
     fig.canvas.mpl_connect('button_press_event', self.onclick) 

    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 
     L = self.ax.axhline(y=y) 
     print(y) 
     ax.axvspan(0, 0, facecolor='y', alpha=0.5, picker=10) 
     self.fig.canvas.draw() 

    def onclick(event): 
     self.fig.canvas.set_title('Selected item came from {}'.format(event.ydata)) 
     print(event.xdata, event.ydata) 

if __name__ == '__main__': 

    plt.ion() 
    p = PointPicker() 
    plt.show() 

假如没有什么疗法的方式来实现我的最终结果,一切都很好,用这种方法,但我不能为我的生命得到标题打印(使用self.fig.canvas.set_title('Selected item came from {}'.format(event.ydata))。

回答

3

您可以使用'button_press_event'连接到一个方法,该方法验证点击发生的距离与yaxis脊椎足够近,然后使用点击的坐标绘制水平线。

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

enter image description here

+0

不错!奇迹般有效。 –

相关问题