如何更改pyplot中各个图例条目的字体大小? [英] How to change fontsize of individual legend entries in pyplot?

查看:31
本文介绍了如何更改pyplot中各个图例条目的字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是控制pyplot中图例中各个条目的字体大小.也就是说,我希望第一个条目为一个尺寸,第二个条目为另一个尺寸.这是我尝试的解决方案,但无效.

What I'm trying to do is control the fontsize of individual entries in a legend in pyplot. That is, I want the first entry to be one size, and the second entry to be another. This was my attempt at a solution, which does not 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()

我期望所有图例条目的默认大小将为小".然后,我获得了Text对象的列表,并将仅单个Text对象的字体大小更改为中.但是,由于某种原因,这会将所有Text对象的字体大小更改为中号,而不仅仅是我实际更改的单个字体.我觉得这很奇怪,因为我可以通过这种方式分别设置其他属性,例如文本颜色.

My expectation is that the default size for all legend entries would 'small'. I then get a list of the Text objects, and change the fontsize for only a single Text object to medium. However, for some reason this changes all Text object fontsizes to medium, rather than just the single one I actually changed. I find this odd since I can individually set other properties such as text color in this manner.

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

Ultimately, I just need some way to change an individual entry's fontsize for a legend.

推荐答案

似乎每个图例条目的字体都是由 matplotlib.font_manager.FontProperties 的实例管理的.关键是:每个条目都没有自己的 FontProperties ...它们都共享相同的内容.这可以通过以下方式验证:

It appears that the font of each legend entry is managed by an instance of matplotlib.font_manager.FontProperties. The thing is: each entry doesn't have its own FontProperties... they all share the same one. This is verified by writing:

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

因此,如果您更改第一个条目的大小,则第二个条目的大小也会随之自动更改.

So if you change the size of the first entry, the size of the second entry is automatically changed along with it.

要解决此问题的技巧"就是为每个图例条目简单地创建一个 FontProperties 的不同实例:

The "hack" to get around this is to simply create a distinct instance of 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()

现在尺寸是正确的:

这篇关于如何更改pyplot中各个图例条目的字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆