Issue
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:
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()
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:
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.