How can I change the fonts of individual legend entries in pyplot?

What I'm trying to do is control the font of individual legend entries in pyplot. That is, I want the first record to be one size and the second another. This was my attempt at a solution that doesn't work.

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(1,5,0.5)
plt.figure(1)
plt.plot(x,x,label='Curve 1')
plt.plot(x,2*x,label='Curve 2')
leg = plt.legend(loc = 0, fontsize = 'small')
leg.get_texts()[0].set_fontsize('medium')
plt.show()

      

I expect the default size for all legend entries to be "small". Then I get a list of Text objects and change the fontsize for just one text object per media. However, for some reason this changes all the fonts of the Text object to medium, not just the one that I actually changed. I find it odd since I can individually set other properties like text color this way.

Ultimately, I just need to change the custom font for the legend in some way.

+5


source to share


2 answers


It seems that the font of each legend entry is instance driven matplotlib.font_manager.FontProperties

. The point is, every entry doesn't have its own FontProperties

... they all have the same. This is confirmed by writing:

>>> t1, t2 = leg.get_texts()
>>> t1.get_fontproperties() is t2.get_fontproperties()
True

      

So, if you resize the first entry, the second entry will automatically resize with it.

The hack to get around this is to simply create a separate instance FontProperties

for each legend entry:



x = np.arange(1,5,0.5)
plt.figure(1)
plt.plot(x,x,label='Curve 1')
plt.plot(x,2*x,label='Curve 2')
leg = plt.legend(loc = 0, fontsize = 'small')

t1, t2 = leg.get_texts()
# here we create the distinct instance
t1._fontproperties = t2._fontproperties.copy()
t1.set_size('medium')

plt.show()

      

And now the dimensions are correct:

enter image description here

+6


source


A much easier way is possible if you enable LaTeX to render text on your charts. You achieve this effortlessly with an extra command line after your "imports":

plt.rc('text', usetex=True)

      

Now you can resize any particular line by specifying with r

at the beginning of the line to be processed with LaTeX and add the command of the desired size for LaTeX inside ( \small, \Large, \Huge,

etc.). For example:

r'\Large Curve 1'

      



Take a look at your customized code. Only minor changes were required!

import numpy as np
import matplotlib.pyplot as plt

plt.rc('text', usetex=True) #Added LaTeX processing

x = np.arange(1,5,0.5)
plt.figure(1)
#Added LaTeX size commands on the formatted String
plt.plot(x,x,label=r'\Large Curve 1')
plt.plot(x,2*x,label=r'\Huge Curve 2')
plt.legend(loc = 0, fontsize = 'small')
#leg.get_texts()[0].set_fontsize('medium')
plt.show()

      

So you get this:

enter image description here

0


source







All Articles