python - 使用 matplotlib 在多个子图之外添加图例

标签 python matplotlib

我正在制作一些图形,每个图形中都有不同数量的子图。 我想在右下角添加图例,但遇到了一些麻烦。 我尝试在右下角添加一个新的子图并仅向其添加图例,但图例后面有一个空的子图。 这就是我现在所站的位置,但无论最后一个子图在哪里,都希望右下角有图例。

fig = plt.figure()
matplotlib.rc('xtick', labelsize=8) 
matplotlib.rc('ytick', labelsize=8)

for line in a[1:]:

        ax = fig.add_subplot(subcol,subrow,counter)
        ax.plot(x,line[3:7],marker='o', color='r', label = 'oral')
        ax.plot(x,line[7:],marker='o', color='b',label = 'physa')
        ax.set_title(line[1],fontsize = 10)
        counter+=1

ax.legend(bbox_to_anchor=(2, 0),loc = 'lower right')
plt.subplots_adjust(left=0.07, right=0.93, wspace=0.25, hspace=0.35)
plt.suptitle('Kegg hedgehog',size=16)
plt.show()

最佳答案

更好的解决办法是

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

这会将图例添加到图中而不是子图中。

适应你的例子,它会是这样的

fig = plt.figure()
matplotlib.rc('xtick', labelsize=8) 
matplotlib.rc('ytick', labelsize=8)

handles = []
for line in a[1:]:

        ax = fig.add_subplot(subcol,subrow,counter)
        l1 = ax.plot(x,line[3:7],marker='o', color='r', label = 'oral')
        l2 = ax.plot(x,line[7:],marker='o', color='b',label = 'physa')
        if not handles:
           handles = [l1, l2]
        ax.set_title(line[1],fontsize = 10)
        counter+=1

fig.legend(handles, ['oral', 'physa'], bbox_to_anchor=(2, 0),loc = 'lower right')
plt.subplots_adjust(left=0.07, right=0.93, wspace=0.25, hspace=0.35)
plt.suptitle('Kegg hedgehog',size=16)
plt.show()

关于python - 使用 matplotlib 在多个子图之外添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23996246/

相关文章:

python - Cython 为应评估为 0.5 的表达式返回 0?

python - 尽管我在数据框中有该列,但在转换数据类型时出现 KeyError

python - "min() arg is an empty sequence"尝试将我的 Pandas plotly 转换为 plotly 时

python - matplotlib imshow 固定方面和垂直颜色条匹配主轴高度

testing - 如何绘制三个参数的组合

python - 如何在运行时将 C 程序的输出连接到 python 程序

python - 具有适当符号的 Numpy 八函数

python - 打印时从字典的值中删除括号

python - Django:将文件添加到表单会出现多个参数错误

matplotlib - 让 Matplotlib 的 GTK Agg 后端尊重用户主题