Home > other >  Matplotlib Legend string formatting / Align
Matplotlib Legend string formatting / Align

Time:02-26

I'm trying to plot a graph with a nicely formatted legend.

import matplotlib.pyplot as plt

test_label ="""\
CL      :1.2565
CM      :1.2565
Tot CD  :1.2565"""

fig, ax = plt.subplots()

foil=[(0, 1), (0, 0), 'black']
ax.plot(*foil, label=test_label)

plt.xlim(-0.5, 1.5)
plt.ylim(-0.75, 0.75)
plt.legend(frameon=False)
plt.show(block=False)

As you can see the test_label is nicely formatted (vertically aligned colons), but this alignment is not preserved when I do the actual plot.

strong text

Could anyone please suggest a way to place this legend in such a way that all colons are aligned vertically ?

CodePudding user response:

You might want to change the font type into monospace.

Code:

import matplotlib.pyplot as plt

test_label ="""\
CL      :1.2565
CM      :1.2565
Tot CD  :1.2565"""

# Change the font type.
plt.rcParams['font.family'] = 'monospace'

fig, ax = plt.subplots()

foil=[(0, 1), (0, 0), 'black']
ax.plot(*foil, label=test_label)

plt.xlim(-0.5, 1.5)
plt.ylim(-0.75, 0.75)
plt.legend(frameon=False)
plt.show(block=False)

Output:

enter image description here

CodePudding user response:

You can set the text justification of the legend to the right so that the numbers have the same number of digits and can be aligned.

import matplotlib.pyplot as plt

test_label ="""\
CL      :1.2565
CM      :1.2565
Tot CD  :1.2565"""

fig, ax = plt.subplots()

foil=[(0, 1), (0, 0), 'black']
ax.plot(*foil, label=test_label)

plt.xlim(-0.5, 1.5)
plt.ylim(-0.75, 0.75)
legend = plt.legend(frameon=False)
for t in legend.get_texts():
    t.set_ha('right')
    
plt.show(block=False)

enter image description here

  • Related