在画图的时候经常需要添加上标或者下标,最常用的方法就是使用latex进行,之前就直接百度了代码复制了,但是发现有时候latex打印出来的字体和我原本的字体并不一样,于是就去找了一下原因。
首先当我们进行打印上标时,网上可以找到一下两种写法:
plt.text('${ha^{-1}}$')
plt.text('$\mathregular{ha^{-1}}$')
这里mathregular其实是告诉电脑这里要用和非latex内容相同的字体,所以如果大家希望latex打印出来的字体和默认字体一样就需要用第二行的代码,另外也可以直接在rc里面设置:
plt.rcParams["mathtext.default"]="regular"
#mathtext.default : it ## The default font to use for math.
## Can be any of the LaTeX font names, including
## the special name "regular" for the same font
## used in regular text.
关于latex的设置大家还可以去matplotlibrc里具体看看,matplotlibrc文件所在路径可以用下面的代码来查找
import matplotlib
print(matplotlib.get_data_path())
但是有时候如果电脑的默认字体和我们想要打印的字体不同时,打印上标就有可能偏移量过高,直接进行中文百度也没有找到结果,最终终于在matplotlib.mathtext这个模块里找到了对应的设置,这里基本上有所有文字的设置。如果偏移量过高可以通过下面的语句进行设置:
import matplotlib
plt.rcParams["mathtext.default"]="regular"
matplotlib.mathtext.FontConstantsBase.sup1 = 0.45
# mathtext.py中的说明如下
class FontConstantsBase:
"""
A set of constants that controls how certain things, such as sub-
and superscripts are laid out. These are all metrics that can't
be reliably retrieved from the font metrics in the font itself.
"""
# Percentage of x-height of additional horiz. space after sub/superscripts
script_space = 0.05
# Percentage of x-height that sub/superscripts drop below the baseline
subdrop = 0.4
# Percentage of x-height that superscripts are raised from the baseline
sup1 = 0.7
# Percentage of x-height that subscripts drop below the baseline
sub1 = 0.3
# Percentage of x-height that subscripts drop below the baseline when a
# superscript is present
sub2 = 0.5
# Percentage of x-height that sub/supercripts are offset relative to the
# nucleus edge for non-slanted nuclei
delta = 0.025
# Additional percentage of last character height above 2/3 of the
# x-height that supercripts are offset relative to the subscript
# for slanted nuclei
delta_slanted = 0.2
# Percentage of x-height that supercripts and subscripts are offset for
# integrals
delta_integral = 0.1
官方链接:
https://matplotlib.org/3.2.1/_modules/matplotlib/mathtext.html#ComputerModernFontConstants