Text alignment using format in matplotlib legend

不打扰是莪最后的温柔 提交于 2021-01-29 18:37:30

问题


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()

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.


回答1:


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'})


来源:https://stackoverflow.com/questions/51721839/text-alignment-using-format-in-matplotlib-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!