Matplotlib 中如何为所有子图创建一个图例
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()
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()
for ax in fig.axes:
axLine, axLabel = ax.get_legend_handles_labels()
lines.extend(axLine)
labels.extend(axLabel)
万一单个子图中存在更多的行和标签,所有的线条句柄和标签都将通过列表 extend
方法添加到 lines
和 labels
列表中。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串