Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we align marker and text in legends vertically in Matplotlib?

Tags:

matplotlib

When the marker in a legend is a dot, dot and text are not aligned vertically. To solve this I tried following:

l = ax.legend()
for text in l.texts:
    text.set_va('center') # Is there some setting for this in matplotlibrc, too??

plt.show()

The vertical alignment of text in a legend seems to be baseline. But no matter whether I choose center, bottom or baseline, etc., things are off: enter image description here

Zooming in, this is what Matplotlib gives us out of the box: enter image description here

What I want is also what other software like Inkscape gives me, when aligning two objects vertically: enter image description here

Can Matplotlib do this for me/us?

like image 302
AltaStatistika Avatar asked Sep 10 '25 15:09

AltaStatistika


1 Answers

This appears to work:

  • Set it to display only a single scatterpoint per legend entry by setting scatterpoints=1 in the call to legend()
  • Set the vertical offset of this point to 0 by setting scatteryoffsets=[0] in the call to legend()
  • After creating the legend, iterate through its text labels and set their vertical alignment to center_baseline, using for t in l.get_texts(): t.set_va('center_baseline')
figure(figsize=(2,2))
scatter([0],[0],marker='s',s=20,label='Thing 1')
scatter([1],[0],marker='s',s=20,label='t')
scatter([2],[0],marker='s',s=20,label='T¹₁')
l = legend(scatterpoints=1,scatteryoffsets=[0],handletextpad=-0.5)
for t in l.get_texts(): t.set_va('center_baseline')
like image 154
MRule Avatar answered Sep 13 '25 13:09

MRule