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

时间:2016-06-14 10:47:24

标签: python matplotlib pyqt legend

我想在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.)

Plot with legend on RHS

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

  

TypeError:legend()至少需要3个参数(给定2个)

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

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

1 个答案:

答案 0 :(得分:6)

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

来自文档:

  

图例(句柄,标签,* args,** kwargs)

     

在图中放置一个图例。 labels是一系列字符串,handles是一系列Line2DPatch个实例。

以下作品:

# 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)  

enter image description here