迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Matplotlib 中如何为所有子图创建一个图例

作者:迹忆客 最近更新:2023/03/17 浏览次数:

Matplotlib figure 类中的 legend 方法,用于将 legend 放置在图形级别而不是 subplot 级别。如果所有子图中线条的图案和标签都相同,则用起来会特别方便。

在 Matplotlib 中使用 figure.legend 方法为所有子图制作单个图例

import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

for ax in fig.axes:
    ax.plot([0, 10], [0, 10], label='linear')

lines, labels = fig.axes[-1].get_legend_handles_labels()
    
fig.legend(lines, labels, loc = 'upper center')

plt.show()

Matplotlib 图例获取图例句柄标签

lines, labels = fig.axes[-1].get_legend_handles_labels()

因为我们假定所有子图具有相同的线条和标签,因此,最后一个 Axes 的句柄和标签可以用于整个图形。

当 Matplotlib 中的线柄和线不同时,使用 figure.legend 方法为所有子图制作单个图例

如果子图之间的线型和标签不同,但是所有子图都需要一个图例,则需要从所有子图中获取所有的线柄和标签。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 501)

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

axes[0, 0].plot(x,
                np.sin(x),
                color = 'k',
                label="sin(x)")
axes[0, 1].plot(x,
                np.cos(x),                
                color = 'b',
                label="cos(x)")
axes[1, 0].plot(x,
                np.sin(x) + np.cos(x),
                color = 'r',
                label="sin(x)+cos(x)")
axes[1, 1].plot(x,
                np.sin(x) - np.cos(x),
                color = 'm',
                label="sin(x)-cos(x)")

lines = []
labels = []

for ax in fig.axes:
    axLine, axLabel = ax.get_legend_handles_labels()
    lines.extend(axLine)
    labels.extend(axLabel)

    
fig.legend(lines, labels,           
           loc = 'upper right')

plt.show()

Matplotlib 图 get_legend_handles_labels 中的 Legend_all 标签

for ax in fig.axes:
    axLine, axLabel = ax.get_legend_handles_labels()
    lines.extend(axLine)
    labels.extend(axLabel)

万一单个子图中存在更多的行和标签,所有的线条句柄和标签都将通过列表 extend 方法添加到 lineslabels 列表中。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便