在Matplotlib中使用stix字体使标签同时呈现斜体和粗体样式

6
我正在尝试使用matplotlib生成图形,并使用“stix”字体(rcParams['mathtext.fontset'] ='stix')以便在文本和数学文本之间具有平滑的字体大小过渡。然而,我希望我的某些数学符号是斜体(标量值),而有些则是斜体粗体(张量)。我不想使用Latex渲染的解决方案,因为那样会弄乱其他事情。
我将给您一个小例子来说明这个问题:
from numpy import *
from matplotlib.pyplot import * 

# Chaning font to stix
rcParams['mathtext.fontset'] = 'stix'

# Some data to constract this plotting example
datax=[0,1,2]
datay=[8,9,10]
datay2=[8,15,10]

fig, ay = subplots()

ay.plot(datax, datay, color="0.", ls='-', label= r"$F_{\alpha}$")
ay.plot(datax, datay2, color="0.", ls='-', label=r"$\mathbf{F_{\alpha}}$")

# Now add the legend with some customizations.
legend = ay.legend(loc='left', shadow=True)

#frame = legend.get_frame()
#frame.set_facecolor('0.90')
xlabel(r"x label",fontsize=18)
ylabel(r'y label', fontsize=18)
grid()

show()

如果您运行代码,第一个标签是斜体,第二个标签是粗体。我该如何实现第二个标签既是粗体又是斜体?

数学文本变成斜体和粗体的问题


我认为这是不可能的。您可能需要使用真正的LaTeX(即usetex=True),然后这个问题可能会有所帮助:https://tex.stackexchange.com/questions/14395/bold-italic-vectors - ImportanceOfBeingErnest
3个回答

9
一些更具体的mathtext参数是必需的:
from numpy import *
from matplotlib.pyplot import *

# Changing font to stix; setting specialized math font properties as directly as possible
rcParams['mathtext.fontset'] = 'custom'
rcParams['mathtext.it'] = 'STIXGeneral:italic'
rcParams['mathtext.bf'] = 'STIXGeneral:italic:bold'

# Some data to construct this plotting example
datax=[0,1,2]
datay=[8,9,10]
datay2=[8,15,10]

fig, ay = subplots()

ay.plot(datax, datay, color="0.", ls='-', label= r"$\mathit{F_{\alpha}}$")
ay.plot(datax, datay2, color="0.", ls='-', label=r"$\mathbf{F_{\alpha}}$")

# Now add the legend with some customizations.
legend = ay.legend(loc='left', shadow=True)

# Using the specialized math font again
xlabel(r"$\mathbf{x}$ label",fontsize=18)
ylabel(r'y label', fontsize=18)
grid()

show()

enter image description here

请注意,我在轴标签中使用了mathbf。可能会将其余部分更改为STIX字体,您可以定义非斜体非粗体的情况:请参见“自定义字体”下的文档
matplotlib画廊中还有至少两个示例可能会有所帮助:一个查看字体系列另一个提醒我们哪些STIX字体是哪些

1
太棒了!1000个赞。我已经阅读了有关mathtext rcParams的文档,但无法弄清楚指定特定stix字体变量的语法。非常感谢。 - SpinUp __ A Davis
1
我也无法从文档中找到答案,我想我不得不阅读一些源代码。但是现在有两个官方示例和一个新的rcParam——添加在答案的末尾。 - cphlewis

0
截至matplotlib版本3.8,现在有\mathbfit命令可用。
import matplotlib.pyplot as plt

plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'Nimbus Roman'
plt.rcParams['mathtext.fontset'] = 'stix'

fig, ax = plt.subplots()
ax.plot([], label= r"italic (default): $F_\alpha$")
ax.plot([], label=r"roman: $\mathrm{F_\alpha}$")
ax.plot([], label=r"bold: $\mathbf{F_\alpha}$")
ax.plot([], label=r"bold and italic: $\mathbfit{F_\alpha}$")
ax.legend(fontsize='xx-large')

bold and italic math text


-3

所以MatplotLib使用LaTeX语法,我的猜测是您可以使用LaTeX语法来获得斜体和粗体,即

 \textbf{\textit{text}}

所以在你的情况下,它将会是:

ay.plot(datax, datay2, color="0.", ls='-', label= r"$\mathbf{ \textit{F_{\alpha}} }$")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接