简体   繁体   English

Matplotlib对数刻度刻度标签,乳胶字体中的减号太长

[英]Matplotlib log-scale tick labels, minus sign too long in latex font

I'm using 'text.usetex': True in matplotib. 我正在使用'text.usetex':matplotib中为True。 This is nice for plots with a linear scale. 这对于具有线性比例的图非常有用。 For a log-scale however, the y-ticks looks like this: 但是,对于对数刻度,y滴答如下所示:

The minus signs in the exponents take a lot of horizontal space in a plot, which is not very nice. 指数中的减号在绘图中占用了大量水平空间,这不是很好。 I want it to rather look like that: 我希望它看起来像这样:

That one is from gnuplot, and it's not using the tex-font. 那是来自gnuplot的,它没有使用tex-font。 I would like to use matplotlib, have it rendered in tex, but the minus signs in 10^{-n} should be shorter. 我想使用matplotlib,将其呈现在tex中,但是10 ^ {-n}中的减号应该更短。 Is that possible? 那可能吗?

The length of the minus sign is a decision of your LaTeX font - in math mode binary and unary minuses have the same length. 负号的长度由您的LaTeX字体决定-在数学模式下,二进制和一进制负号具有相同的长度。 According to this answer you can make your own labels. 根据此答案,您可以制作自己的标签。 Try this: 尝试这个:

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

to obtain: 获得: 结果图

Dietrich gave you a nice answer, but if you want to keep all the functionality (non-base 10, non-integer exponents) of LogFormatter , then you might create your own formatter: Dietrich给了您一个很好的答案,但是如果您想保留LogFormatter所有功能(非基10,非整数指数),那么您可以创建自己的格式化程序:

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

The only thing this really does is to grab the output of the usual formatter, find the possible negative exponents and change the LaTeX code of the math minus into something else. 唯一要做的就是获取常规格式化程序的输出,找到可能的负指数,并将数学减法的LaTeX代码更改为其他内容。 Of course, if you invent some creative LaTex with \\scalebox or something equivalent, you may do so. 当然,如果您使用\\scalebox或类似的东西发明了一些有创意的LaTex,则可以这样做。

This: 这个:

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

creates: 创建:

在此处输入图片说明

The good thing about this solution is that it changes the output as minimally as possible. 该解决方案的优点在于,它会尽可能最小地更改输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM