如何在pyplot中更改单个图例条目的字体大小?

7
我想做的是在pyplot中控制图例中各个条目的字体大小。也就是说,我希望第一个条目的大小与第二个条目不同。以下是我尝试的解决方案,但并没有起作用。
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()

我希望所有图例条目的默认大小都为“小”。然后,我获取Text对象列表,并仅更改单个Text对象的字体大小为中等。但是,由于某种原因,这会将所有Text对象的字体大小更改为中等,而不仅仅是我实际更改的单个对象。我认为这很奇怪,因为我可以以这种方式单独设置其他属性,例如文本颜色。

最终,我只需要一种方法来更改图例中单个条目的字体大小。

2个回答

9

似乎每个图例条目的字体都由matplotlib.font_manager.FontProperties的一个实例管理。问题是:每个条目没有自己的FontProperties...它们都共享同一个。这通过编写以下内容进行验证:

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

如果您更改第一个条目的大小,则第二个条目的大小也会自动更改。

绕过此问题的“技巧”是为每个图例条目创建一个不同的 FontProperties 实例:

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()

现在尺寸是正确的:

这里输入图片描述


不确定是何时添加的,但这对我也有效(matplotlib 1.5.3):t1.set_fontproperties(t1.get_fontproperties())。这样做的好处是不依赖于受保护的文本属性(即 _fontproperties)。请注意,即使将 FontProperties 分配给您从中获取它们的同一对象(在此示例中为 t1),它仍会在内部进行复制。另请参见 此处 - FernAndr

1

如果您在绘图时启用LaTeX进行文本呈现,则可以使用更简单的方法。您只需在“imports”后添加一个额外的命令行即可轻松实现:

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

现在,您可以通过在要使用LaTeX处理的字符串开头指定r,并在内部添加所需的size command for LaTeX(如\small、\Large、\Huge等)来更改任何特定字符串的大小。 例如:
r'\Large Curve 1'

看看你改编后的代码,只需要做出了一些小修改!

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()

所以你得到这个:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接