在Matplotlib中如何居中带有换行的图例标题

12
我使用以下代码在matplotlib中显示图例标题:legend title
import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
plt.plot(all_x, all_y)

# Add legend, title and axis labels
plt.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='lower right', title='hello hello hello \n world')
plt.show()

正如您所见,"world"没有居中对齐。我希望它能够居中对齐,可以通过手动添加空格来实现:

enter image description here

import matplotlib.pyplot as plt

# data 
all_x = [10,20,30]
all_y = [[1,3], [1.5,2.9],[3,2]]

# Plot
plt.plot(all_x, all_y)

# Add legend, title and axis labels
plt.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='lower right', title='hello hello hello \n        world')
plt.show()

在此输入图像描述

但那是一个繁琐的解决方案。

有没有更合适的方法来实现这个目标?


1
l = plt.legend([ 'Lag ' + str(lag) for lag in all_x], loc='best', title='你好你好你好 \n 世界') l.get_title().set_ha('center') 这似乎可以工作,但对于较长的字符串,它会过度向左对齐。 - Srivatsan
@ThePredator 感谢您的建议! - Franck Dernoncourt
欢迎提出任何其他想法。 - Franck Dernoncourt
1个回答

17

多行 Matplotlib 文本的对齐方式由关键字参数 multialignment 控制(请参见此处的示例http://matplotlib.org/examples/pylab_examples/multiline.html)。

因此,您可以按以下方式使图例标题文本居中:

l = plt.legend(['Lag ' + str(lag) for lag in all_x], loc='lower right',
               title='hello hello hello \n world')
plt.setp(l.get_title(), multialignment='center')

只是插一句,如果其他人想把实际标签居中,.get_texts()也是一个传奇方法: plt.setp(l.get_texts(), multialignment='center') - Sealander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接