我想在pyqt GUI中为matplotlib(python)中的多个图创建一个自定义图例.(pyqt建议不要使用pyplot,因此必须使用面向对象的方法).
多个绘图将出现在网格中,但用户可以定义要显示的绘图数量.我希望图例出现在所有图的右侧,因此我不能简单地为最后的轴绘制图例.我希望为整个图形创建图例而不仅仅是最后一个轴(类似于pyplot中的plt.figlegend).
在其他地方看到的例子中,这需要参考绘制的线条.同样,我无法做到这一点,因为用户可以选择在图表上显示哪些线条,我宁愿总是显示所有可能的线条,无论它们当前是否显示.
(注意下面的示例代码使用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', …Run Code Online (Sandbox Code Playgroud)