栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

如何在matplotlib中创建可拖动的图例?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在matplotlib中创建可拖动的图例?

注意:现在已内置到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-users组发送了电子邮件,John Hunter很好,可以将我的解决方案添加到SVN HEAD中。

2010年1月28日星期四,下午3:02,亚当·弗雷泽(Adam Fraser)写道:

我以为我会分享一个可拖动的图例问题的解决方案,因为它使我永远吸收了邮件列表中所有分散的知识…

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

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

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

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



转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640005.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号