简体   繁体   English

使Matplotlib在数学模式下显示衬线字体

[英]Make matplotlib display serif font in math mode

How can I get the font to be Times New Roman when using maths typing in matplotlib. 在使用matplotlib进行数学运算时,如何获得字体为Times New Roman的字体。 The default font is italic, and I'm trying to make it match the other axes titles. 默认字体为斜体,我正在尝试使其与其他坐标轴标题匹配。

I'm trying to use \\mathrm{}: 我正在尝试使用\\ mathrm {}:

plt.xlabel(r"$\frac{\mathrm{1}}{{\mathrm{Distance}}^2 \ (\mathrm{m}^2)}$")

as suggested on a matplotlib website ( https://matplotlib.org/users/mathtext.html ) but it still appears as a sans-serif font. 就像在matplotlib网站( https://matplotlib.org/users/mathtext.html )上所建议的一样,但它仍然以无衬线字体显示。 Is there a way I can make this into Times new Roman? 有什么方法可以使我成为时代新罗马人吗? Thanks! 谢谢!

Interpreting the question you are looking for serif font in both the text on the axes, as well as any MathText using on the plot. 解释您要在轴上的文本以及绘图中使用的任何MathText中寻找衬线字体的问题。

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "serif"
plt.rcParams["mathtext.fontset"] = "dejavuserif"

plt.xlabel(r"$\frac{\mathrm{1}}{{\mathrm{Distance}}^2 \ (\mathrm{m}^2)}$")
plt.ylabel("Some normal text")
plt.tight_layout()
plt.show()

在此处输入图片说明

Another use case is to want a serif font in math mode, but only for a specific character. 另一个用例是希望在数学模式下使用衬线字体,但仅适用于特定字符。 A solution is to set the fontset to custom , then set a serif font for only the mathcal (calligraphic) set of characters. 一种解决方案是将fontset设置为custom ,然后仅对mathcal (书法)字符集设置衬线字体。 Here, I'm also setting the font style to italic: 在这里,我还将字体样式设置为斜体:

import matplotlib.pyplot as plt

plt.rcParams['mathtext.fontset'] = 'custom'
plt.rcParams['mathtext.cal'] = 'stix:italic'  # changes only the mathcal subfamily

Then, get a single serif character (d, here), but keep the rest as the default math font with: 然后,获取单个衬线字符(此处为d),但其余部分保留为默认的数学字体,具体方法如下:

plt.ylabel(r'Label ($a^b = \mathcal{d}$)')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM