代码之家  ›  专栏  ›  技术社区  ›  Ian

是否有Matplotlib.ticker.logFormatterScination的非数学版本?

  •  7
  • Ian  · 技术社区  · 6 年前

    我正在尝试使用带“乳胶”的“ pgf_”绘制带有对数Y轴的图形,即所有文本格式都由pdflatex完成。在matplotlib rc参数中,我定义了要使用的字体。我的问题来了:标准 matplotlib.ticker.logformatterscintotation formatter使用了数学文本,因此是一种不适合其余字体(sans-serif)的数学字体。

    如何使用 matplotlib.ticker 中的格式化程序格式化Y轴标签,以便使用上标的幂得到格式化为10幂的标签?更具体地说:我如何得到这些Yticklabels的格式相同,但字体从Xticklabels?

    我已经尝试使用由 matplotlib.ticker提供的不同的格式化程序,但没有一个格式化程序的指数按我想要的方式写入。

    下面是我对一个MWE的意思的一个例子。

    import matplotlib as mpl
    
    使用(“PGF”)
    含乳胶的PGF_={
    “pgf.texsystem”:“pdflatex”,
    “font.family”:“无衬线”,
    “text.usetex”:错误,
    “pgf.preamble”:。[
    r“\usepackage[utf8x]inputenc”,
    r“\usepackage tgheros,”,tex gyre heros sans-serif
    r“\usepackage[T1]fontenc”
    ]
    }
    
    mpl.rcparams.update(pgf_with_乳胶)
    将matplotlib.pyplot导入为plt
    
    Fig=plt.Fig(图尺寸=[3,2])
    ax=图添加子批次(111)
    ax.设置刻度(“对数”)。
    ax.minorticks关闭()
    ax.set xlabel(“sans-serif字体标签”)
    ax.set_ylabel(“数学字体标签”)
    plt.gca()。设置ylim([10000])
    plt.gcf()。紧凑布局()
    
    
    plt.savefig(“.pdf”.格式(“test”))
    < /代码> 
    
    

    警告:必须在系统上安装一个Tex分发版才能运行此程序。我用的是Miktex 2.9。另外还有python 3.6.2matplotlib 2.1.2pgf_with_latex,即所有文本格式都由pdflatex完成。在matplotlib rc参数中,我定义了要使用的字体。我的问题来了:标准matplotlib.ticker.LogFormatterSciNotation格式化程序使用了数学文本,因此使用了不适合其余字体(无衬线字体)的数学字体。

    如何使用格式设置工具设置Y轴标签的格式matplotlib.ticker所以我得到了格式为10次幂和上标幂的标签?更具体地说:我如何得到这些Yticklabels的格式相同,但字体从Xticklabels?

    我已经尝试使用由提供的不同格式化程序Matplotlib.ticker但是没有一个指数是按照我想要的方式写的。

    下面是我对一个MWE的意思的一个例子。 example plot

    import matplotlib as mpl
    
    mpl.use('pgf')
    pgf_with_latex = {
            "pgf.texsystem": "pdflatex",
            "font.family": "sans-serif",
            "text.usetex": False,
            "pgf.preamble": [
                r"\usepackage[utf8x]{inputenc}",
                r"\usepackage{tgheros}",  # TeX Gyre Heros sans serif
                r"\usepackage[T1]{fontenc}"
                ]
            }
    
    mpl.rcParams.update(pgf_with_latex)
    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=[3, 2])
    ax = fig.add_subplot(111)
    ax.set_yscale("log")
    ax.minorticks_off()
    ax.set_xlabel("sans-serif font label")
    ax.set_ylabel("math font label")
    plt.gca().set_ylim([1, 10000])
    plt.gcf().tight_layout()
    
    
    plt.savefig('{}.pdf'.format("test"))
    

    警告:必须在系统上安装一个Tex分发版才能运行此程序。我用的是Miktex 2.9。还有python 3.6.2和matplotlib 2.1.2。

    2 回复  |  直到 6 年前
        1
  •  2
  •   ImportanceOfBeingErnest    6 年前

    您可以使用 “10\textsuperscript x” 子类来格式化记号,其中 x is the exponent.这将不使用数学模式tex,即no $ 在文本周围签名,因此将使用前导码中指定的text font(在本例中,字体不带衬线)。

    import matplotlib as mpl
    从matplotlib.ticker导入logformatterexponent
    
    使用(“PGF”)
    含乳胶的PGF_={
    “pgf.texsystem”:“pdflatex”,
    “font.family”:“无衬线”,
    “text.usetex”:错误,
    “pgf.preamble”:。[
    r“\usepackage[utf8x]inputenc”,
    r“\usepackage tgheros,”,tex gyre heros sans-serif
    r“\usepackage[T1]fontenc”
    ]
    }
    mpl.rcparams.update(pgf_with_乳胶)
    将matplotlib.pyplot导入为plt
    
    类logformatterextmode(logformatterexponent):
    定义调用(self,x,pos=none):
    x=logFormatterExponent.\u调用(self,x,pos)
    S=R“10\文本上标”.格式(X)
    返回S
    
    Fig=plt.Fig(图尺寸=[3,2])
    ax=图添加子批次(111)
    ax.设置刻度(“对数”)。
    ax.yaxis.set_major_formatter(logformattertextmode())
    ax.minorticks关闭()
    ax.set xlabel(“sans-serif字体标签”)
    ax.设置“ylabel”(“文本模式Tex标签”)。
    plt.gca()。设置ylim([0.01,20000])
    plt.gcf()。紧凑布局()
    
    
    plt.savefig(“.pdf”.格式(“test”))
    < /代码> 
    
    

    这不会使用数学模式tex,也就是说,不$在文本周围签名,因此将使用序言中指定的文本字体(在本例中是不带衬线的字体)。

    import matplotlib as mpl
    from matplotlib.ticker import LogFormatterExponent
    
    mpl.use('pgf')
    pgf_with_latex = {
            "pgf.texsystem": "pdflatex",
            "font.family": "sans-serif",
            "text.usetex": False,
            "pgf.preamble": [
                r"\usepackage[utf8x]{inputenc}",
                r"\usepackage{tgheros}",  # TeX Gyre Heros sans serif
                r"\usepackage[T1]{fontenc}"
                ]
            }
    mpl.rcParams.update(pgf_with_latex)
    import matplotlib.pyplot as plt
    
    class LogFormatterTexTextMode(LogFormatterExponent):
        def __call__(self, x, pos=None):
            x = LogFormatterExponent.__call__(self, x,pos)
            s = r"10\textsuperscript{{{}}}".format(x)
            return s
    
    fig = plt.figure(figsize=[3, 2])
    ax = fig.add_subplot(111)
    ax.set_yscale("log")
    ax.yaxis.set_major_formatter(LogFormatterTexTextMode())
    ax.minorticks_off()
    ax.set_xlabel("sans-serif font label")
    ax.set_ylabel("text mode tex label")
    plt.gca().set_ylim([0.01, 20000])
    plt.gcf().tight_layout()
    
    
    plt.savefig('{}.pdf'.format("test"))
    

    enter image description here

        2
  •  0
  •   Joooeey    6 年前

    您可以定义自己的用Unicode进行科学记数的FuncForMatter。

    这个答案中给出了一个几乎完整的上标转换程序。我刚刚加了个减号。

    下面是一个实现:

    编码:utf-8-*- 从数学导入日志10 上标=dict(zip(U“-0123456789”,U“___________”)) def unicode符号(x,pos): “用Unicode表示数字的科学符号” 功率=int(log10(x)) 尾数=x/(10**幂) 上标=U“”。联接(Unicode(Power)中C的上标[C]) 如果尾数==1: 返回“10%s”上标 其他: 返回“%.2f x 10%s%”(尾数,上标) 格式设置工具=mpl.ticker.funcormatter(Unicode符号) ax.yaxis.set_major_格式化程序(格式化程序) < /代码>

    要这样做,需要在脚本顶部指定编码:utf-8。如果您不想这样做,可以按照我链接的答案中的说明转义Unicode字符。

    . 我刚刚加了个负号。

    下面是一个实现:

    # -*- coding: utf-8 -*-
    from math import log10
    
    SUPERSCRIPTS = dict(zip(u"-0123456789", u"⁻⁰¹²³⁴⁵⁶⁷⁸⁹"))
    def unicode_sci_notation(x, pos):
        """Scientific notation of number with unicode"""
        power = int(log10(x))
        mantissa = x/(10**power)
        superscript = u''.join(SUPERSCRIPTS[c] for c in unicode(power))
        if mantissa == 1:
            return '10%s' % superscript
        else:
            return '%.2f x 10%s' % (mantissa, superscript)
    formatter = mpl.ticker.FuncFormatter(unicode_sci_notation)
    
    ax.yaxis.set_major_formatter(formatter)
    

    要这样做,需要在脚本顶部指定编码:utf-8。如果您不想这样做,可以按照我链接的答案中的说明转义Unicode字符。

    enter image description here