在 matplotlib 中更改 ax.text 的字体

Changing the font of ax.text in matplotlib

我正在使用 matplotlib 制作 python 图。

在代码的开头,我使用:

plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']

为了更改我绘图中文本的字体。

我也用:

ax.text(0.5,0.5, r'$test_{1}$', horizontalalignment='center', verticalalignment='center', size=18)

但是这段文字不是 Times New Roman。

如何制作 ax.text Times New Roman?

谢谢。

1。参数fontdict

Axes.text matplotlib documentation 说:

If fontdict is None, the defaults are determined by your rc parameters.

因此您必须在 ax.text() 中包含 fontdict=None,以便显示其在 rcParams 中指定的字体。

ax.text(..., fontdict=None)

fontdict 参数可用自 matplotlib 2.0.0

2。数学表达式

此外,对于像 $a=b$the docs 这样的数学表达式来说:

This default [font] can be changed using the mathtext.default rcParam. This is useful, for example, to use the same font as regular non-math text for math text, by setting it to regular.

所以你还需要将默认字体设置为'regular':

rcParams['mathtext.default'] = 'regular'

此选项至少自 matplotlib 2.1.0

起可用

3。范例

您的代码现在应该类似于:

import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']
plt.rcParams['mathtext.default'] = 'regular'

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])

ax.text(0.5, 0.5, '$example$', horizontalalignment='center', 
        verticalalignment='center', size=18, fontdict=None)

plt.show()