使用Matplotlib图例中的格式进行文本对齐 [英] Text alignment using format in matplotlib legend
问题描述
我正在尝试使两个单词在matplotlib中的图例中对齐.使用print语句,我可以使用可用于格式化的工具(<用于左对齐,>用于右对齐)进行此操作,但是在图例中,结果会有所不同.
I'm trying to get two words aligned in a legend in matplotlib. With the print statement I can do this using the tools available to format (< for left alignment, > for right alignment), but in the legend this has a different result.
import matplotlib.pyplot as plt
import numpy as np
str1 = r'{:<18} {:>12}'.format('HadGEM2-ES'+',', r'$\lambda$')
str2 = r'{:<18} {:>12}'.format('inmcm4'+',', r'$\lambda$')
print(str1)
print(str2)
plt.plot(np.arange(10), label=str1)
plt.plot(0.8*np.arange(10), label=str2)
plt.legend()
这样print语句的输出将变得整洁:
So that the output for the print statement neatly becomes:
HadGEM2-ES, $\lambda$
inmcm4, $\lambda$
但该图以不同的方式显示了图例.如何使图中的图例对齐.
But the figure shows the legends differently. How do I get the legend in the figure to be aligned.
推荐答案
由于控制台中使用的字体是等宽字体,因此该间隔与print语句正确.您可以通过以下方式在图例中复制它:
The spacing is correct with the print statement because the font used in the console is monospace. You can replicate this in the legend with:
plt.legend(prop={'family': 'monospace'})
这篇关于使用Matplotlib图例中的格式进行文本对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!