0

The code below:

import numpy as np
import matplotlib.pyplot as plt
plt.plot(x, x+np.log10(2),  color = 'blue',  linestyle = ':', label = r'$ doubled \quad \bf{ y=2*x }$')
plt.plot(x, x-np.log10(2),  color = 'green', linestyle = ':', label = r'$ halved  \quad \bf{ y=0.5*x }$')
plt.legend(fontsize = 15)

produces a plot where the mathematical part of the second label y=0.5*x is shifted to the left relative to the mathematical part of the first label y=2*x; is it possible to modify something (automatically) so that both y start at exactly the same level?

Well, by "automatically" I mean some instruction/code that would avoid manually adding \, symbols in the second label, until the alignment works more or less well...

enter image description here

Andrew
  • 926
  • 2
  • 17
  • 24
  • This is tricky to do with variable width fonts. You would need to pre-compute the width of each leading word. I suggest to use a monospace font as a quick and easy workaround. – mozway Mar 28 '22 at 09:08
  • this one can help u https://stackoverflow.com/questions/7936034/text-alignment-in-a-matplotlib-legend. Looks like they figure out the problem. – DOBBYLABS Mar 28 '22 at 09:19

1 Answers1

0

In case it helps:

import numpy as np
import matplotlib.pyplot as plt

texts = ['doubled', 'halved']
maxt = len(max(texts, key=len))

texts = [elem.ljust(maxt) for elem in texts]

plt.plot(x, x+np.log10(2),  color = 'blue',  linestyle = ':', 
         label = texts[0] + r'$ \quad \bf{ y=2*x }$')
plt.plot(x, x-np.log10(2),  color = 'green', linestyle = ':', 
         label = texts[1] + r'$ \quad \bf{ y=0.5*x }$')
plt.legend(prop={'family':'monospace', 'size': 16})

enter image description here

Andrew
  • 926
  • 2
  • 17
  • 24