Reputation: 305
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.
Upvotes: 0
Views: 630
Reputation: 145
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'})
Upvotes: 2