2015-09-29 56 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