2015-09-29 53 views
0

我有一個有三個不同長度和寬度的圖例。我試圖找到一種方法將它們很好地放置在劇情上。目前我將它們放在默認的loc=上,這對於處理垂直位置非常有用。問題在於,默認情況下,這些圖例是右對齊的,看起來很亂。Matplotlib:如何垂直對齊多個圖例

有沒有辦法使用默認的loc=將它們放置在圖上,但讓它們左對齊?

例如: 從legend guide

import matplotlib.pyplot as plt 

line1, = plt.plot([1,2,3], label="Line 1", linestyle='--') 
line2, = plt.plot([3,2,1], label="Line 2\nThis is a \nvery long\nlegend", linewidth=4) 
line3, = plt.plot([2,2,2], label="Can this be left justified?") 

# Create a legend for the first two lines. 
# 'loc' puts them in a nice place on the right. 
first_legend = plt.legend(handles=[line1], loc=1) 
second_legend = plt.legend(handles=[line2], loc=5) 

# Add the legends manually to the current Axes. 
ax = plt.gca().add_artist(first_legend) 
ax = plt.gca().add_artist(second_legend) 

# Create another legend for the last line. 
plt.legend(handles=[line3], loc=4) 

plt.show() 

哪個給出了這樣的

three legend plot

現在我真的想是要左對齊的傳說,但仍對劇情的右側。像這樣:

enter image description here

我知道我可以在特定的位置,但要做到這一點,我需要同時指定x和y COORDS,這將是繁瑣的,因爲所有3具有可變高度和寬度放置。

+2

你的建議是有問題的,因爲它需要matplotlib收縮主軸線,以允許底傳說留「圖像上」,而不是被截斷,右軸通常是非常接近的邊緣顯示器。所以我認爲你必須手動放置圖例並縮小主軸來完成你想要的。 – daryl

+0

daryl,我可以使用textwrap控制圖例的寬度。所以水平範圍是可以的。問題是垂直放置它們。但我開始認爲你是對的,看起來像手動放置是最好的方法。 – jprockbelly

回答

2

您想要的地方,您可以使用bbox_to_anchor定位圖例精確:

fig, ax = plt.subplots() 
line1, = ax.plot([1,2,3], label="Line 1", linestyle='--') 
line2, = ax.plot([3,2,1], label="Line 2\nThis is a \nvery long\nlegend", linewidth=4) 
line3, = ax.plot([2,2,2], label="Can this be left justified?") 

# Create a legend for the first two lines. 
# 'loc' sets anchor position of the legend frame relative to itself, 
# bbox_to_anchor puts legend's anchor to (x, y) in axes coordinates. 
first_legend = ax.legend(handles=[line1], loc='upper left', bbox_to_anchor=(0.65, 1)) 
second_legend = ax.legend(handles=[line2], loc='center left', bbox_to_anchor=(0.65, 0.5)) 

# Add the legends manually to the current Axes. 
ax.add_artist(first_legend) 
ax.add_artist(second_legend) 

# Create another legend for the last line. 
ax.legend(handles=[line3], loc='lower left', bbox_to_anchor=(0.65, 0)) 

plt.show() 

你唯一需要的數量是傳說bbox_to_anchorx位置對齊到(在上面的例子中0.65)。

enter image description here

+0

感謝Primer,這真的很有用。 – jprockbelly

+1

當我用'fig.savefig(「test.png」)'運行這個例子時,底部圖例在PNG文件中被截斷。 – daryl

+0

daryl,可以通過添加緊湊的佈局參數'plt.savefig(「test.png」,bbox_inches ='tight')輕鬆修復' – jprockbelly