matplotlib 跨多个子图共享的单个图例

例子

有时您会有一个子图网格,并且您希望有一个图例来描述每个子图的所有线条,如下图所示。

为此,您需要为图形创建全局图例,而不是在级别创建图例(这将为每个子图创建单独的图例)。这是通过调用实现的,如以下代码的代码所示。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()