如何在 Matplotlib 中更改圖例條目之間的垂直間距?
圖例在傳達關於繪圖元素的資訊方面起著至關重要的作用,這些資訊主要包含在 Matplotlib 中,Matplotlib 是一個流行的用於資料視覺化的 Python 庫,但有時在處理複雜的視覺化時,圖例條目之間的預設垂直間距可能並不理想。本文探討了修改和自定義 Matplotlib 中圖例條目之間垂直間距的技術,允許使用者增強其繪圖的可讀性和美觀性。
什麼是 Matpltlib 圖表中的圖例?
在 Matplotlib 圖表中,圖例是一個鍵或指南,它提供了對圖表中顯示的各種元素的解釋。它有助於識別圖表中使用的不同顏色、標記或線條樣式的含義。圖例通常包含與每個元素相關的標籤或符號及其相應的描述。它允許檢視者理解圖表中資料的表示或類別。圖例是傳達資訊和提高圖表可解釋性的寶貴組成部分。
如何在 Matplotlib 中更改圖例條目之間的垂直間距?
要更改 Matplotlib 中圖例條目之間的垂直間距,您可以按照以下步驟操作:
匯入所需的庫:
import matplotlib.pyplot as plt
建立繪圖並新增圖例:
# Plotting code... plt.legend()
獲取圖例控制代碼和標籤:
handles, labels = plt.gca().get_legend_handles_labels()
使用修改後的垂直間距建立一個新的圖例:
# Specify the desired vertical spacing (adjust the value as needed) spacing = 1.0 # Create a new legend with modified spacing new_legend = plt.legend(handles, labels, loc='upper right', ncol=1, frameon=False, bbox_to_anchor=(1.1, 1.1), title='Legend', borderpad=spacing)
在上面的程式碼中,spacing 是一個變數,表示圖例條目之間所需的垂直間距。您可以根據需要調整此值。bbox_to_anchor 引數設定圖例的位置,您可以修改其座標以將其放置在圖表中的適當位置。
移除舊圖例:
# Remove the old legend plt.gca().get_legend().remove()
將新圖例新增到繪圖中:
# Add the new legend to the plot plt.gca().add_artist(new_legend)
顯示繪圖:
plt.show()
透過遵循這些步驟,您可以根據自己的喜好自定義 Matplotlib 中圖例條目之間的垂直間距。
以下是使用鳶尾花資料集和散點圖在 Matplotlib 中更改圖例條目之間垂直間距的程式示例:
示例
import matplotlib.pyplot as plt import numpy as np # Load an example dataset (Iris dataset) from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target target_names = iris.target_names # Plotting the data plt.scatter(X[:, 0], X[:, 1], c=y) plt.xlabel('Sepal length') plt.ylabel('Sepal width') # Create a legend with custom vertical spacing legend = plt.legend(target_names, title='Species', loc='lower right') # Set the vertical spacing between legend entries legend.get_frame().set_linewidth(0.0) # Remove border around the legend legend.get_title().set_fontsize('12') # Set the font size of the legend title for handle in legend.legendHandles: handle.set_sizes([30]) # Set the marker size of the legend entries legend._legend_box.align = "left" # Align legend entries vertically # Adjust the vertical spacing between legend entries legend._set_loc(1) plt.subplots_adjust(right=0.8) # Display the plot plt.show()
輸出
要更改圖例條目之間的垂直間距,我們使用 legend.get_frame()、legend.get_title() 和 legend.legendHandles 訪問圖例屬性。我們刪除了圖例周圍的邊框,設定了圖例標題的字型大小,設定了圖例條目的標記大小,並垂直對齊了圖例條目。legend._set_loc(1) 行調整了垂直間距,plt.subplots_adjust() 用於調整繪圖的佈局。
以下是使用鳶尾花資料集和條形圖在 Matplotlib 中更改圖例條目之間垂直間距的程式示例:
示例
import matplotlib.pyplot as plt import numpy as np # Load an example dataset (Iris dataset) from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target target_names = iris.target_names # Calculate the average sepal length for each species avg_sepal_length = [] for i in range(len(target_names)): avg_sepal_length.append(np.mean(X[y == i, 0])) # Plotting the data plt.bar(target_names, avg_sepal_length) plt.xlabel('Species') plt.ylabel('Average Sepal Length') # Create a legend with custom vertical spacing legend = plt.legend(['Average Sepal Length'], loc='upper right') # Set the vertical spacing between legend entries legend.get_frame().set_linewidth(0.0) # Remove border around the legend legend.get_title().set_fontsize('12') # Set the font size of the legend title legend._legend_box.align = "left" # Align legend entries vertically # Adjust the vertical spacing between legend entries legend._set_loc(1) plt.subplots_adjust(right=0.8) # Display the plot plt.show()
輸出
結論
總之,可以透過訪問和修改圖例物件的屬性來實現更改 Matplotlib 中圖例條目之間的垂直間距。透過刪除圖例的邊框,調整標題的字型大小,並垂直對齊圖例條目,我們可以根據自己的喜好自定義間距。這允許更好地控制圖例在圖表中的佈局和顯示。透過使用這些技術,我們可以增強圖形的清晰度和視覺吸引力,使它們對觀眾來說更具資訊性和吸引力。