'Matplotlib Legend string formatting / Align

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 ?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 r-beginners