Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading