2010-03-29 125 views
37

我正在matplotlib中的轴对象上绘制图例,但声称将它放置在智能位置的默认位置似乎不起作用。理想情况下,我希望用户可以拖动图例。如何才能做到这一点?如何在matplotlib中创建一个可拖动的图例?

+0

亚当:考虑到这是相当大的,彻底的,并足够相关的Matplotlib发行包括,鉴于(我觉得)你删除你原来的问题,你能不能包括在顶部的两句话这个Q,所以用户可以了解这个代码的用途(从而不必读代码本身)。还有不错的工作,顺便说一下,我的方式+1。 – doug 2010-03-30 06:12:25

+0

谢谢道格。我按照你的建议在顶部说了这个问题。希望这会有所帮助。 :] – 2010-03-30 14:48:22

+0

这可以扩展为次轴? – denfromufa 2014-09-29 06:34:43

回答

28

注:这是现在内置matplotlib

leg = plt.legend() 
if leg: 
    leg.draggable() 

将如预期


嗯,我发现位和散落的邮件列表中的解决方案的部分。我想出了一个代码不错的模块化块,你可以删除并使用......这就是:

class DraggableLegend: 
    def __init__(self, legend): 
     self.legend = legend 
     self.gotLegend = False 
     legend.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) 
     legend.figure.canvas.mpl_connect('pick_event', self.on_pick) 
     legend.figure.canvas.mpl_connect('button_release_event', self.on_release) 
     legend.set_picker(self.my_legend_picker) 

    def on_motion(self, evt): 
     if self.gotLegend: 
      dx = evt.x - self.mouse_x 
      dy = evt.y - self.mouse_y 
      loc_in_canvas = self.legend_x + dx, self.legend_y + dy 
      loc_in_norm_axes = self.legend.parent.transAxes.inverted().transform_point(loc_in_canvas) 
      self.legend._loc = tuple(loc_in_norm_axes) 
      self.legend.figure.canvas.draw() 

    def my_legend_picker(self, legend, evt): 
     return self.legend.legendPatch.contains(evt) 

    def on_pick(self, evt): 
     if evt.artist == self.legend: 
      bbox = self.legend.get_window_extent() 
      self.mouse_x = evt.mouseevent.x 
      self.mouse_y = evt.mouseevent.y 
      self.legend_x = bbox.xmin 
      self.legend_y = bbox.ymin 
      self.gotLegend = 1 

    def on_release(self, event): 
     if self.gotLegend: 
      self.gotLegend = False 

...在你的代码...

def draw(self): 
    ax = self.figure.add_subplot(111) 
    scatter = ax.scatter(np.random.randn(100), np.random.randn(100)) 


legend = DraggableLegend(ax.legend()) 

我通过电子邮件发送了Matplotlib用户组,John Hunter非常友好,可以将我的解决方案添加到SVN HEAD中。

于星期四,2010年1月28日在下午3点02分,亚当 弗雷泽 写道:

我想我会分享一个解决拖动传说的问题,因为 花了我一辈子以吸收邮件列表上的所有零散知识...

酷 - 很好的例子。我将代码添加到 legend.py。现在你可以做

腿= ax.legend()
leg.draggable()

启用拖动模式。您可以通过 反复调用此功能来切换 可拖动状态。

我希望这对使用matplotlib的人有帮助。

13

在更新版本的Matplotlib(v1.0.1)中,这是内置的。

def draw(self): 
    ax = self.figure.add_subplot(111) 
    scatter = ax.scatter(np.random.randn(100), np.random.randn(100)) 
    legend = ax.legend() 
    legend.draggable(state=True) 

如果您以交互方式使用matplotlib(例如,在IPython的pylab模式下)。

plot(range(10), range(10), label="test label") 
plot(range(10), [5 for x in range(10)], label="another test") 
l = legend() 
l.draggable(True) 
相关问题