Matplotlib 中如何更改图例字体大小

我们有不同的方法来设置 Matplotlib 中图例中文本的字体大小。

rcParams 方法指定字体大小

rcParams 是处理 Matplotlib 属性和默认样式的字典。

1. plt.rc('legend', fontsize= ) 方法

fontsize 可以是单位为 points 的整数,也可以是表征大小的字符串,例如

xx--small
x-small
small
medium
large
x-large
xx-large
plt.rc('legend', fontsize=16)
plt.rc('legend', fontsize='medium')

Matplotlib 中如何更改图例字体大小

2. plt.rcparams.update() 方法

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
params = {'legend.fontsize': 16,
          'legend.handlelength': 3}
plt.rcParams.update(params)
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()

legend.fontsize 指定图例字体大小,而 legend.handlelength 指定图例句柄长度,以字体大小为单位。

plt.rcParams.update(params) 用上面定义的字典 params 来更新 Matplotlib 属性和样式。

或者,你可以通过将键值放在括号 [] 中来更新 rcParams 字典,

plt.rcParams['legend.fontsize'] = 16
plt.rcParams['legend.handlelength'] = 16

plt.legend(fontsize= ) 指定图例字体大小的方法

plt.legend(fontsize=) 可以在创建每个图例时指定图例字体大小。

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.legend(fontsize=16, loc='upper right')
plt.show()

图例中的 prop 属性

图例中的 prop 属性可以设置图例的单个字体大小。prop 是来自 matplotlib.font_manager.FontProperties 中的关键字构成的字典。

plt.legend(prop={'size': 16})

例:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label="sin(x)")
plt.legend(prop={'size':16}, loc='best')
plt.show()