【问题标题】:Is there a non-math version of matplotlib.ticker.LogFormatterSciNotation?是否有 matplotlib.ticker.LogFormatterSciNotation 的非数学版本?
【发布时间】:2018-09-11 14:04:11
【问题描述】:

我正在尝试使用pgf_with_latex 绘制带有对数 y 轴的图形,即所有文本格式都由 pdflatex 完成。在我的 matplotlib rc 参数中,我定义了要使用的字体。我的问题来了:标准的matplotlib.ticker.LogFormatterSciNotation 格式化程序使用了数学文本,因此使用了数学字体,它不适合其余字体(无衬线)。

如何使用来自matplotlib.ticker 的格式化程序格式化 y 轴标签,以便将标签格式化为 10 的幂和上标幂?更具体地说:如何让这些 yticklabels 以相同的方式格式化,但使用 xticklabels 中的字体?

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

下面是我所说的 MWE 的示例。

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。

【问题讨论】:

  • 这里使用"text.usetex": False,的原因是什么?那不应该是True吗?如果您在乳胶文档中使用\usepackage{tgheros},它会影响数学字体吗? (即像This is text and $a= \sin{b}$ 这样的东西会在纯乳胶文档中以相同的无衬线字体打印吗?)
  • @ImportanceOfBeingErnest 我使用"text.usetex": False,因为显然在序言中加载的字体仅以这种方式考虑。如果我启用该标志,TeX 将使用拉丁现代。 tgheros 不会影响任何地方的数学字体。我的问题是,如何防止 matplotlib 使用数学字体,同时仍然保持标签不变?
  • 所以本质上你想要在数学模式之外实现类似$10^{2}$ 的东西。我不知道这是否可能。但是,如果您找到一种在纯乳胶中执行此操作的方法,则可以相应地调整格式化程序;如果没有,matplotlib 无能为力。我认为通常人们会尝试在这种情况下使用看起来与他们的文本字体足够相似的数学字体。
  • @ImportanceOfBeingErnest 这正是我想要做的!也许有人知道某种解决方法......
  • 我想这将是一个两阶段的问题。因此,为了找到一种在 tex 数学模式之外产生 $10^{2}$ 的方法,您可能首先尝试在 tex.stackexchange.com 找到解决方案(通过在那里搜索或提问)。 如果事实证明是可能的,在此处链接到此类解决方案将允许将其用于 matplotlib 格式化。

标签: python matplotlib plot formatting latex


【解决方案1】:

您可以将LogFormatterExponent 子类化以使用"10\textsuperscript{x}" 格式化刻度,其中x 是指数。这不会使用数学模式 tex,即文本周围没有 $ 符号,因此将使用序言中指定的 textfont(在这种情况下是没有衬线的字体)。

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"))

【讨论】:

  • 这正是我想要的!谢谢!
【解决方案2】:

您可以定义自己的 FuncFormatter 以 unicode 进行科学记数法。

this answer 中提供了几乎完整的上标转换器。我只是加了减号。

这是一个实现:

# -*- 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 字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2011-10-18
    • 2011-11-05
    • 2012-05-18
    相关资源
    最近更新 更多