如何在matplotlib中为数学文本和常规文本使用不同的字体类型?
我正在使用 ieeconf 这个 LaTeX 类来写文档。为了生成文档中的图表,我使用 matplotlib 1.2。出于某种原因,ieeconf 类的普通文本使用的是 Times 字体,而数学文本则使用 Computer modern roman 字体。如果我在 matplotlib 中使用以下的 matplotlibrc 文件
font.family : serif
font.serif : Times
text.usetex : True
那么图表中的普通文本(非数学文本)看起来和文档中的普通文本一模一样。不过,图表中的数学文本和文档中的数学文本看起来就不一样。如果我改用 font.serif : Computer Modern Roman
,那么情况就反过来了,数学文本看起来一样,但普通文本就不一样了。
我该如何让 matplotlib 在普通文本和数学文本中使用不同的字体呢?
2 个回答
1
从 3.4版本开始,你可以通过 math_fontfamily
这个参数来实现这个功能:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(6, 5))
# A simple plot for the background.
ax.plot(range(11), color="0.9")
# A text mixing normal text and math text.
msg = (r"Normal Text. $Text\ in\ math\ mode:\ "
r"\int_{0}^{\infty } x^2 dx$")
# Set the text in the plot.
ax.text(1, 7, msg, size=12, math_fontfamily='cm')
# Set another font for the next text.
ax.text(1, 3, msg, size=12, math_fontfamily='dejavuserif')
# *math_fontfamily* can be used in most places where there is text,
# like in the title:
ax.set_title(r"$Title\ in\ math\ mode:\ \int_{0}^{\infty } x^2 dx$",
math_fontfamily='stixsans', size=14)
# Note that the normal text is not changed by *math_fontfamily*.
plt.show()