單個圖例共享多個子圖
有時你會有一個子圖網格,並且你希望有一個圖例描述每個子圖的所有線,如下圖所示。
為此,你需要為圖形建立一個全域性圖例,而不是在軸級別建立圖例 (這將為每個子圖建立一個單獨的圖例)。這可以通過呼叫 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()
的其他論據純粹是可選的,只是幫助微調傳奇的美學。