kga*_*har 3 python tkinter matplotlib legend
我正在开发一个Tkinter
集成matplotlib
的 GUI,我在同一张图上绘制 128 条线matplotlib
。为了区分这些行,我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 )
Run Code Online (Sandbox Code Playgroud)
图例工作得很好,但是当我尝试向其中添加超过 15 个元素时,它的长度不断增加,并且在可见的 15 个元素上方和下方添加的标签不可行。
我从matplotlib.axes.Axes.legend文档中检查了滚动选项,但找不到任何此类选项。是否可以为此添加滚动选项legend
?
如果您有鼠标滚轮,则可以使用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()
Run Code Online (Sandbox Code Playgroud)