XYZ
XYZ

Reputation: 385

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 ?

Upvotes: 0

Views: 1409

Answers (2)

r-beginners
r-beginners

Reputation: 35230

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

Upvotes: 0

quasi-human
quasi-human

Reputation: 1928

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

Upvotes: 1

Related Questions