Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tab alignment in legend of Matplotlib Plot

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?

plot

like image 491
Guiste Avatar asked Oct 19 '25 05:10

Guiste


1 Answers

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

enter image description here

like image 135
ImportanceOfBeingErnest Avatar answered Oct 22 '25 04:10

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!