Tab alignment in legend of Matplotlib Plot

喜夏-厌秋 提交于 2019-11-28 09:52:07

问题


I would like to create a plot with a legend aligning the text of the different curves. Here is a minimal working example:

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,100)
plt.plot(x,np.sin(x),'-',label=r'1st, second, third, a$_b$')
plt.plot(x,np.cos(x),'--',label=r'fourth, 5th, 5$_{fo}$, sixth')
plt.legend()
plt.show()

I want the labels to align in the legend, so get something like:

1st     second     third       a$_b$    
fourth  5th        5$_{fo}$    sixth

Is there a way of doing this?


回答1:


An easy option would be to use a monospace font and fill the required space with blanks.

import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,10,100)
plt.plot(x,np.sin(x),'-', label='1st     second   third   a$_b$')
plt.plot(x,np.cos(x),'--',label='fourth  5th      5$_{fo}$      sixth')
plt.legend(prop={'family': 'DejaVu Sans Mono'})
plt.show()



来源:https://stackoverflow.com/questions/48211853/tab-alignment-in-legend-of-matplotlib-plot

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