简体   繁体   English

使用 matplotlib 将图例中的标记与图例标题左对齐

[英]Left aligning markers in legend with legend title using matplotlib

I'm trying to make a plot with Matplotlib, and I would look to have the legend on the top left.我正在尝试用 Matplotlib 制作 plot,我希望左上角有图例。 Without a legend title this is working fine with the code below, but when I add a legend title which is longer than the legend labels, the markers shift.如果没有图例标题,这可以很好地使用下面的代码,但是当我添加一个比图例标签长的图例标题时,标记会移动。

Is there any way I can prevent this and have them all align to the left?有什么办法可以防止这种情况并让它们都向左对齐?

import numpy as np
import matplotlib.pyplot as plt

# Data
x = np.arange(0, 4 * np.pi ,0.1)
y = np.sin(x)

fig, axs = plt.subplots(1, 2, figsize=(8, 4))

# Working fine without legend title
axs[0].plot(x, y, label='sin')
axs[0].legend(title='', loc='lower left', bbox_to_anchor=(0,1), facecolor='white', edgecolor='white', framealpha=1)

# Position shifts when using long legend title
axs[1].plot(x, y, label='sin')
axs[1].legend(title='Some longer title', loc='lower left', bbox_to_anchor=(0,1), facecolor='white', edgecolor='white', framealpha=1)

plt.show()

剧情传奇标题

For me, your code does something similar to what you want to have by me simply changing the bbox_to_anchor argument from the axs[1].legend() command.对我来说,您的代码所做的事情类似于您想要的,我只需更改bbox_to_anchor axs[1].legend()命令中的 bbox_to_anchor 参数即可。

Now it reads: bbox_to_anchor=(-0.1,1) and it produces the below.现在它显示为: bbox_to_anchor=(-0.1,1)并产生以下内容。 Of course, you can change the first value to -0.15 or so if you want it to be more to the left.当然,如果您希望它更靠左,您可以将第一个值更改为-0.15左右。

输出

Full code:完整代码:

import numpy as np
import matplotlib.pyplot as plt

# Data
x = np.arange(0, 4 * np.pi ,0.1)
y = np.sin(x)

fig, axs = plt.subplots(1, 2, figsize=(8, 4))

# Working fine without legend title
axs[0].plot(x, y, label='sin')
axs[0].legend(title='', loc='lower left', bbox_to_anchor=(0,1), facecolor='white', edgecolor='white', framealpha=1)

# Position shifts when using long legend title
axs[1].plot(x, y, label='sin')
axs[1].legend(title='Some longer title', loc='lower left', bbox_to_anchor=(-0.1,1), facecolor='white', edgecolor='white', framealpha=1)

plt.show()

I found a workaround in a still unresolved issue on GitHub .在 GitHub 上的一个仍未解决的问题中找到了一种解决方法。 Apparently the default alignment is "center", which can be changed like this.显然默认的 alignment 是“中心”,可以这样改变。

axs[1].get_legend()._legend_box.align = "left"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM