首页 文章

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

提问于
浏览
1

我想在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(handles = [blue_line,green_line]),则python会产生错误:

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

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

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

1 回答

  • 6

    你得到的错误是因为Figure.legend要求你传递它 handleslabels .

    来自文档:

    图例(手柄,标签,* args,** kwargs)在图中放置一个图例 . 标签是一系列字符串,句柄是一系列Line2D或Patch实例 .

    以下作品:

    # 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

相关问题