单个图例共享多个子图
有时你会有一个子图网格,并且你希望有一个图例描述每个子图的所有线,如下图所示。
为此,你需要为图形创建一个全局图例,而不是在轴级别创建图例 (这将为每个子图创建一个单独的图例)。这可以通过调用 fig.legend()
来实现,如下面代码的代码所示。
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10,4))
fig.suptitle('Example of a Single Legend Shared Across Multiple Subplots')
# The data
x = [1, 2, 3]
y1 = [1, 2, 3]
y2 = [3, 1, 3]
y3 = [1, 3, 1]
y4 = [2, 2, 3]
# Labels to use in the legend for each line
line_labels = ["Line A", "Line B", "Line C", "Line D"]
# Create the sub-plots, assigning a different color for each line.
# Also store the line objects created
l1 = ax1.plot(x, y1, color="red")[0]
l2 = ax2.plot(x, y2, color="green")[0]
l3 = ax3.plot(x, y3, color="blue")[0]
l4 = ax3.plot(x, y4, color="orange")[0] # A second line in the third subplot
# Create the legend
fig.legend([l1, l2, l3, l4], # The line objects
labels=line_labels, # The labels for each line
loc="center right", # Position of legend
borderaxespad=0.1, # Small spacing around legend box
title="Legend Title" # Title for the legend
)
# Adjust the scaling factor to fit your legend text completely outside the plot
# (smaller value results in more space being made for the legend)
plt.subplots_adjust(right=0.85)
plt.show()
有关上述示例的注意事项如下:
l1 = ax1.plot(x, y1, color="red")[0]
当调用 plot()
时,它返回 line2D 对象的列表。在这种情况下,它只返回一个包含一个 line2D 对象的列表,该对象使用 [0]
索引提取,并存储在 l1
中。
我们感兴趣的所有 line2D 对象的列表都包含在图例中,需要作为 fig.legend()
的第一个参数传递。fig.legend()
的第二个论点也是必要的。它应该是一个字符串列表,用作图例中每一行的标签。
传递给 fig.legend()
的其他论据纯粹是可选的,只是帮助微调传奇的美学。