python - 更改matplotlib中ax.text的字体

标签 python matplotlib fonts

我正在使用 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.

因此您还需要将默认字体设置为“常规”:

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

enter image description here

关于python - 更改matplotlib中ax.text的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102830/

相关文章:

python - 尝试使用 Python 解析 XLS (XML) 文件

python - 语法怪癖或为什么有效的 python

python - 使用 Matplotlib 绘制椭圆体

python - 如何让 matplotlib 和 latex 一起工作?

Windows:从 cmd/.bat 文件安装字体

ios - 设置UItextview的字体

python - 是否有 python 代码来解析 geoPDF 文件以获取投影和图像数据? geoPDF2KML 工具?

python - 在 Enthought Canopy IDE 中执行脚本时 matplotlib.figure() 不起作用

python - Matplotlib 中的一半或四分之一极 map ?

css - 可以找出psd中使用gimp的字体吗?或者在 ubuntu 上使用其他应用程序?