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

问题描述 投票:0回答:4

以下代码生成的轴刻度线标签的字体不是 Helvetica,但仍然是默认的 Serif 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()
python latex matplotlib
4个回答
23
投票

我认为这里的混乱源于你混合了 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 内部数学文本渲染器使用的字体集,并且对 TeX 没有影响:

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

当我想要 TeX 中的所有无衬线字体时,我使用的解决方案是使用 cmbright 包,可以通过添加以下内容来打开它:

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

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


20
投票

好的,这对我有用。替换以下行:

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

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

这样:

from matplotlib.pyplot import gca
a = gca()
a.set_xticklabels(a.get_xticks(), fontProperties)
a.set_yticklabels(a.get_yticks(), fontProperties)

您在原始代码中所做的对我来说是有意义的,但我通过这种方式得到了不同的结果。奇怪。


12
投票

我刚刚找到了一个简单的方法,你可以尝试一下。 只需调用 .xticks 方法并将字体名称作为用户设置的参数即可。

例如

import matplotlib.pyplot as plt
plt.figure()
#... do the plot you want...
plt.yticks(fontname = "Times New Roman")  # This argument will change the font.
plt.show()

0
投票

如果打印出来

ax.get_xticklabels()
,应该就清楚发生了什么事情。

[Text(-0.2, 0, '$\\mathdefault{−0.2}$'),
 Text(0.0, 0, '$\\mathdefault{0.0}$'),
 Text(0.2, 0, '$\\mathdefault{0.2}$'),
 Text(0.4000000000000001, 0, '$\\mathdefault{0.4}$'),
 Text(0.6000000000000001, 0, '$\\mathdefault{0.6}$'),
 Text(0.8, 0, '$\\mathdefault{0.8}$'),
 Text(1.0000000000000002, 0, '$\\mathdefault{1.0}$'),
 Text(1.2000000000000002, 0, '$\\mathdefault{1.2}$')]

刻度标签是用 LaTeX 代码渲染的

$\\mathdefault{...}$

因此,一种方法是重新定义

\mathdefault
命令。

rc('text.latex', preamble=r'\def\mathdefault{\mathsf}')

另一种方法是使用

StrMethodFormatter
credit),但这似乎是一个坏主意,因为它会丢弃
ScalarFormatter
所做的所有辛苦工作。

from matplotlib.ticker import StrMethodFormatter
formatter=StrMethodFormatter('$\\mathsf{{{x:.3g}}}$')
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)
© www.soinside.com 2019 - 2024. All rights reserved.