简单的传说

假设你在同一个图中有多条线,每条线都有不同的颜色,并且你希望制作一个图例来说明每条线代表的内容。你可以通过在调用 plot() 时将标签传递给每个行来执行此操作,例如,以下行将标记为 “我的行 1”

ax.plot(x, y1, color="red", label="My Line 1")

这将指定将出现在该行的图例中的文本。现在为了使实际的图例可见,我们可以调用 ax.legend()

默认情况下,它会在图表右上角的框内创建一个图例。你可以将参数传递给 legend() 来自定义它。例如,我们可以将它放在右下角,并在框架周围放置框架,并通过调用以下内容为图例创建标题:

ax.legend(loc="lower right", title="Legend Title", frameon=False)

以下是一个例子:

StackOverflow 文档

import matplotlib.pyplot as plt

# The data
x =  [1, 2, 3]
y1 = [2,  15, 27]
y2 = [10, 40, 45]
y3 = [5,  25, 40]

# Initialize the figure and axes
fig, ax = plt.subplots(1, figsize=(8, 6))

# Set the title for the figure
fig.suptitle('Simple Legend Example ', fontsize=15)

# Draw all the lines in the same plot, assigning a label for each one to be
# shown in the legend
ax.plot(x, y1, color="red", label="My Line 1")
ax.plot(x, y2, color="green", label="My Line 2")
ax.plot(x, y3, color="blue", label="My Line 3")

# Add a legend with title, position it on the lower right (loc) with no box framing (frameon)
ax.legend(loc="lower right", title="Legend Title", frameon=False)

# Show the plot
plt.show()