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

Reserved whitespace in matplotlib legend label

Let’s say I have two arrays.

array1 = ['foofoo', 'bar']
array2 = ['foo', 'bar']

I could print each possible combination of these two arrays as such.

for A in array1:
    for B in array2:
        print('{} {}'.format(A, B))
>>>
foofoo foo
foofoo bar
bar foo
bar bar

That’s pretty ugly, so I can reserve whitespace when printing so the second part aligns, like so:

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

for A in array1:
    for B in array2:
        print('{:7s} {}'.format(A, B))
>>>
foofoo  foo
foofoo  bar
bar     foo
bar     bar

That’s much prettier. I tried to do the same for the legend labels, however it does not work:

x = np.linspace(0,50, 100)

array1 = ['foofoo', 'bar']
array2 = ['foo', 'bar']

for A in array1:
    for B in array2:

        y = [random.random() for x in x]
        y.sort()

        legend_label = r"{:7s} {}".format(A, B)
        plt.plot(x,y, label=legend_label)
    
plt.legend()

enter image description here

How can I achieve the desired behaviour of reserving whitespace within the matplotlib legend labels, so that I could align it within columns as shown in the print('{:7s} {}'.format(A, B)) example.

>Solution :

You need to use a monospace font to be able to align on the number of characters:

plt.legend(prop={'family': 'monospace'})

output:

aligned legend

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