python - 使用 Latex 进行渲染时,如何更改 matplotlib 图中的轴刻度字体?

标签 python latex matplotlib

以下代码生成的轴刻度标签的字体不是 Helvetica,但仍然是默认的衬线 Computer Modern。非常感谢任何建议。

from matplotlib import rc, font_manager
from numpy import arange, cos, pi
from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, \
grid, savefig, show

sizeOfFont = 12
fontProperties = {'family':'sans-serif','sans-serif':['Helvetica'],
    'weight' : 'normal', 'size' : sizeOfFont}
ticks_font = font_manager.FontProperties(family='Helvetica', style='normal',
    size=sizeOfFont, weight='normal', stretch='normal')
rc('text', usetex=True)
rc('font',**fontProperties)
figure(1, figsize=(6,4))
ax = axes([0.1, 0.1, 0.8, 0.7])
t = arange(0.0, 1.0+0.01, 0.01)
s = cos(2*2*pi*t)+2
plot(t, s)

for label in ax.get_xticklabels():
    label.set_fontproperties(ticks_font)

for label in ax.get_yticklabels():
    label.set_fontproperties(ticks_font)

xlabel(r'\textbf{time (s)}')
ylabel(r'\textit{voltage (mV)}',fontsize=16,family='Helvetica')
title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
    fontsize=16, color='r')
grid(True)
savefig('tex_demo.pdf')

show()

最佳答案

我认为这里的混淆源于您混合了 TeX 和非 TeX 字体命令。

这将打开 TeX 模式,因此所有文本都使用外部 TeX 安装呈现:

rc('text', usetex=True)

在这一行中,将其设置为 sans-serif 将传递给 TeX,但 TeX 无法使用特定的 ttf 字体名称,因此第二部分(涉及 Helvetica)被忽略。并且在 TeX 中设置默认正文文本不会(默认情况下)更改数学字体。这是(不幸的是标准的 TeX 行为)。

rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})

这会影响 matplotlib 内部 mathtext 渲染器使用的字体集,对 TeX 没有影响:

rc('mathtext', fontset='stixsans')

当我希望所有无衬线字体都脱离 TeX 时,我使用的解决方案是使用 cmbright 包,可以通过添加:

rc('text.latex', preamble=r'\usepackage{cmbright}')

如果您还没有 cmbright LaTeX 包,则可能需要安装它。

关于python - 使用 Latex 进行渲染时,如何更改 matplotlib 图中的轴刻度字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12322738/

相关文章:

python - Django - 使用 for 循环从列表创建模型字段

python - 无法在 ubuntu 中显示 IPython 对象,但在 colab 输出中显示

latex - 在LaTeX中使用xcookybooky,我有很多成分,但它确实进入下一页

jupyter-notebook - iPython 笔记本中的 Real LaTeX

python - 最适合平滑 3D 表面的矩形网格

python - Mac 和 Linux 中 lxml.etree.tostring() 中的缩进有所不同

python - 如何在 matplotlib 中使用绘图文件?

python - 在 Matplotlib 中加载文本文件时出错

r - 短标题 knitr 中的 fig.scap 不起作用?

python - 如何使用 PySide2 在 matplotlib 中显示图形?