4

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

Guiste
  • 449
  • 1
  • 5
  • 16
  • Yes there probably is a way. What have you tried? – DavidG Jan 11 '18 at 16:40
  • I searched a lot, but could not find anything, yet... Something like a latex tabular environment might be possible? – Guiste Jan 11 '18 at 16:42
  • 3
    Possible duplicate of [tabular legend layout for matplotlib](https://stackoverflow.com/questions/25830780/tabular-legend-layout-for-matplotlib) – DavidG Jan 11 '18 at 16:42
  • I looked at this, but this is not exactly what I want, I think – Guiste Jan 11 '18 at 16:43
  • @DavidG If that is truly helpful for the solution, please post an answer here. I think it will be helpful for many people having a similar problem – Guiste Jan 11 '18 at 23:02

1 Answers1

4

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

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Well, this is not really what I was looking for. I was searching for an automated solution, I don't really want to put in the spaces by hand, nor do I want to use a monospace font (would like to use latex equations also) – Guiste Jan 11 '18 at 22:54
  • There is a link in the comments above to a similar question the solution to which you may adapt for your case. The answer here is just to show a quick and dirty way, in case the linked answer would be too complicated to implement. – ImportanceOfBeingErnest Jan 11 '18 at 23:07
  • any idea on how to achieve the same if you are using ''text.usetex' in 'rcParams'? – TheoryX Sep 08 '20 at 13:52
  • doesn't work using "annotate" for example... – sol Feb 02 '22 at 13:53