【问题标题】:Adding Scroll button to matlibplot axes legend将滚动按钮添加到 matlibplot 轴图例
【发布时间】:2019-09-15 17:31:57
【问题描述】:

我正在开发 Tkintermatplotlib 集成 GUI,我正在同一个 matplotlib 图形上绘制 128 条线。为了区分这些行,我使用以下行添加data legend

matplotlib.axis.legend(handle, self.data.label, loc='center left', bbox_to_anchor=(1, 0.5), title='Data series', prop={'size': 10}, fancybox=True ) 

图例工作得很好,但是当我尝试向它添加超过 15 个元素时,它的长度不断增加,并且在可见 15 个上方和下方添加的标签不可行。

我从matplotlib.axes.Axes.legend 文档中检查了滚动选项,但找不到任何此类选项。是否可以为此legend. 添加滚动选项?

【问题讨论】:

  • 我不认为这是可能的,但mpldatacursor 可能是一个大传奇的替代方案。
  • @fhdrsdg,谢谢你的建议。

标签: python matplotlib tkinter legend


【解决方案1】:

如果您有鼠标滚轮,您可以使用scroll_event 来上下滚动图例。

import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
import numpy as np

n = 50
t = np.linspace(0,20,51)
data = np.cumsum(np.random.randn(51,n), axis=0)

fig, ax = plt.subplots()
fig.subplots_adjust(right=0.78)
ax.set_prop_cycle(color=plt.cm.gist_rainbow(np.linspace(0,1,data.shape[1])))

for i in range(data.shape[1]):
    ax.plot(t, data[:,i], label=f"Label {i}")


legend = ax.legend(loc="upper left", bbox_to_anchor=(1.02, 0, 0.07, 1))

# pixels to scroll per mousewheel event
d = {"down" : 30, "up" : -30}

def func(evt):
    if legend.contains(evt):
        bbox = legend.get_bbox_to_anchor()
        bbox = Bbox.from_bounds(bbox.x0, bbox.y0+d[evt.button], bbox.width, bbox.height)
        tr = legend.axes.transAxes.inverted()
        legend.set_bbox_to_anchor(bbox.transformed(tr))
        fig.canvas.draw_idle()

fig.canvas.mpl_connect("scroll_event", func)

plt.show()

【讨论】:

  • 感谢您的解决方案!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多