Matplotlib:如何垂直对齐多个图例

时间:2015-09-29 03:18:48

标签: python matplotlib legend

我的情节有三个不同长度和宽度的图例。我正试图找到一种方法将它们很好地放在情节上。目前我正在使用默认loc=放置它们,这对于处理垂直放置非常有用。问题在于,默认情况下,图例是右对齐的,看起来很混乱。

有没有办法使用默认的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坐标,因为所有3个坐标都有不同的高度和宽度,所以它们会很繁琐。

1 个答案:

答案 0 :(得分: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()

您需要的唯一号码是x位置“bbox_to_anchor与{(1 {}}对齐(){<1}}。

enter image description here