Matplotlib对数刻度标签,LaTeX字体中减号过长

3
我在matplotib中使用了'text.usetex': True。这对于线性比例尺的图表很好用。但是对于对数比例尺,y轴刻度看起来像这样: 指数中的减号占用了很多水平空间,这不太好看。我想让它看起来更像这样: 那个来自gnuplot,它没有使用tex-font。我想使用matplotlib,在tex中呈现它,但是10^{-n}中的减号应该更短。这可能吗?
2个回答

5

减号的长度取决于您的LaTeX字体-在数学模式下,二进制和一元负号的长度相同。根据这个答案,您可以制作自己的标签。尝试这样做:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import ticker


mpl.rcParams['text.usetex']=True
mpl.rcParams['text.latex.unicode']=True

def my_formatter_fun(x, p):
    """ Own formatting function """
    return r"$10$\textsuperscript{%i}" % np.log10(x)  #  raw string to avoid "\\"


x = np.linspace(1e-6,1,1000)
y = x**2

fg = plt.figure(1); fg.clf()
ax = fg.add_subplot(1, 1, 1)
ax.semilogx(x, x**2)
ax.set_title("$10^{-3}$ versus $10$\\textsuperscript{-3} versus "
             "10\\textsuperscript{-3}")
# Use own formatter:
ax.get_xaxis().set_major_formatter(ticker.FuncFormatter(my_formatter_fun))

fg.canvas.draw()
plt.show()

获取:生成的图表


非常感谢!我最喜欢“10\textsuperscript{-3}”版本,并且从现在开始将使用您的优秀函数! - thomasfermi

4
给出了一个不错的答案,但如果您想保留的所有功能(非十进制、非整数指数),那么您可能需要创建自己的格式化程序:
import matplotlib.ticker
import matplotlib
import re

# create a definition for the short hyphen
matplotlib.rcParams["text.latex.preamble"].append(r'\mathchardef\mhyphen="2D')

class MyLogFormatter(matplotlib.ticker.LogFormatterMathtext):
    def __call__(self, x, pos=None):
        # call the original LogFormatter
        rv = matplotlib.ticker.LogFormatterMathtext.__call__(self, x, pos)

        # check if we really use TeX
        if matplotlib.rcParams["text.usetex"]:
            # if we have the string ^{- there is a negative exponent
            # where the minus sign is replaced by the short hyphen
            rv = re.sub(r'\^\{-', r'^{\mhyphen', rv)

        return rv

这个功能的主要作用是获取通常格式化程序的输出,找到可能存在的负指数,并将数学减号的LaTeX代码更改为其他内容。当然,如果您使用\scalebox或等效物发明一些创意LaTex,也可以这样做。
import matplotlib.pyplot as plt
import numpy as np

matplotlib.rcParams["text.usetex"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
ax.semilogy(np.linspace(0,5,200), np.exp(np.linspace(-2,3,200)*np.log(10)))
ax.yaxis.set_major_formatter(MyLogFormatter())
fig.savefig("/tmp/shorthyphen.png")

创建:

在此输入图片描述

这个解决方案的好处是尽可能地最小化了输出的变化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接