轴上的科学记数法(文学风格)-如何更改默认字体?

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

我需要在 matplotlib 中的两个轴上使用特定字体的文学风格的科学记数法。

在我的搜索中,我发现了这个问题,其中包含来自 ImportanceOfBeingErnest 的文学式科学记数法的答案: 在轴上显示小数位和科学记数法

但没有有关更改字体的详细信息。

我的代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

fig,ax=plt.subplots(1,1,figsize=[7,7])

x=np.linspace(0,0.1,10**3)
y=x**2

ax.plot(x,y)

# code from ImportanceOfBeingErnest
class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.2e"):
        self.fmt = fmt
    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s =  r'%s{\times}%s' % (significand, exponent)
        else:
            s =  r'%s%s' % (significand, exponent)
        return "${}$".format(s)

# Format with 2 decimal places
plt.gca().xaxis.set_major_formatter(MathTextSciFormatter("%1.2e"))
plt.gca().yaxis.set_major_formatter(MathTextSciFormatter("%1.2e"))
# end of code from ImportanceOfBeingErnest

plt.xticks(rotation=45,font="Arial",fontsize=20)

for tick in ax.get_yticklabels():
    tick.set_fontname("Arial")

结果: Graph from code

实现了文学式的科学记数法,但两种改变字体的方法都没有实现。有趣的是,字体大小可以改变。

任何人都可以提供使用此表示法更改字体的解决方案吗?

matplotlib 3.5.3

python matplotlib fonts axis-labels scientific-notation
1个回答
0
投票

您正在使用

matplotlib
的内部数学文本渲染器和
r'$...$'
语法,但您仅更改常规文本的字体。你可以用

import matplotlib as mpl

mpl.rcParams["mathtext.fontset"] = 'custom'
mpl.rcParams['mathtext.rm']='Arimo'

更改各处的数学字体,这可能就是您所追求的。 Arimo 是一种免费字体,在度量上与 Arial 兼容。有关自定义粗体、书法等单个字体的详细信息,请参阅文档

或者您可以使用外部 TeX 渲染器

mpl.rc('text', usetex=True)

但是您需要提供必要的 LaTeX 序言才能使用 Arial 字体。

© www.soinside.com 2019 - 2024. All rights reserved.