如何在Matplotlib中为图例行添加标题?
要在Matplotlib中为图例行添加标题,可以按照以下步骤进行操作:
- 设置图形大小并调整子图之间和周围的填充。
-
使用NumPy创建 y 数据点。
-
创建 标记 和 标签 的列表。
-
创建图形和子图集。
-
使用 plot() 方法绘制线条,具有不同的标签和标记。
-
获取一半图形的绘制处理程序。
-
获取图例的标签。
-
将图例放置在图形上。
-
使用 show() 方法显示图形。
示例
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
y = np.exp(-np.arange(5))
markers = ["s", "o", "*"]
labels = ["one", "two"]
fig, ax = plt.subplots()
for i in range(6):
ax.plot(y * i + i / 2., marker=markers[i // 2], label=labels[i % 2])
h, l = ax.get_legend_handles_labels()
ph = [plt.plot([], marker="", ls="")[0]] * 2
handles = ph + h
labels = ["Title 1:", "Title 2:"] + l
plt.legend(handles, labels, ncol=4)
plt.show()