我正在使用 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()
关于python - 更改matplotlib中ax.text的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102830/