matplotlib (python) - 在没有 pyplot 的情况下为多个图创建单个自定义图例

matplotlib (python) - create single custom legend for multiple plots WITHOUT pyplot

我想在 pyqt GUI 的 matplotlib (python) 中为多个绘图创建自定义图例。 (pyqt建议不要使用pyplot,所以必须使用面向对象的方法)。

多个绘图将出现在一个网格中,但用户可以定义显示多少个绘图。我希望图例出现在所有图的右侧,因此我不能简单地为最后绘制的轴创建图例。我希望为整个图形创建图例,而不仅仅是最后一个轴(类似于 plt.figlegend in pyplot)。

在我见过的示例中 elsewhere,这需要引用绘制的线条。同样,我不能这样做,因为用户可以选择在图表上显示哪些线条,我宁愿图例始终显示所有可能的线条,无论它们当前是否显示。

(注意下面的示例代码使用了 pyplot 但我的最终版本不能)

import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np

fig = plt.figure()

# Create plots in 2x2 grid
for plot in range(4):
    # Create plots
    x = np.arange(0, 10, 0.1)
    y = np.random.randn(len(x))
    y2 = np.random.randn(len(x))
    ax = fig.add_subplot(2,2,plot+1)
    plt.plot(x, y, label="y")
    plt.plot(x, y2, label="y2")

# Create custom legend
blue_line = mlines.Line2D([], [], color='blue',markersize=15, label='Blue line')
green_line = mlines.Line2D([], [], color='green', markersize=15, label='Green line')
ax.legend(handles=[blue_line,green_line],bbox_to_anchor=(1.05, 0),  loc='lower left', borderaxespad=0.)

如果我将 ax.legend 更改为: fig.legend(句柄=[blue_line,green_line]) 然后 python 产生错误:

TypeError: legend() takes at least 3 arguments (2 given)

(我猜是因为没有引用线点)

感谢您提供的任何帮助 - 我已经研究了一个星期了!

您收到的错误是因为 Figure.legend 要求您同时传递 handleslabels

来自文档:

legend(handles, labels, *args, **kwargs)

Place a legend in the figure. labels are a sequence of strings, handles is a sequence of Line2D or Patch instances.

以下作品:

# Create custom legend
blue_line = mlines.Line2D([], [], color='blue',markersize=15, label='Blue line')
green_line = mlines.Line2D([], [], color='green', markersize=15, label='Green line')

handles = [blue_line,green_line]
labels = [h.get_label() for h in handles] 

fig.legend(handles=handles, labels=labels)