Matplotlib对数刻度刻度标签,乳胶字体中的减号太长 [英] Matplotlib log-scale tick labels, minus sign too long in latex font

查看:143
本文介绍了Matplotlib对数刻度刻度标签,乳胶字体中的减号太长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用'text.usetex':matplotib中为True.这对于具有线性比例的图非常有用.但是,对于对数刻度,y滴答如下所示:

I'm using 'text.usetex': True in matplotib. This is nice for plots with a linear scale. For a log-scale however, the y-ticks looks like this:

指数中的减号在绘图中占据了很多水平空间,这不是很好.我希望它看起来像这样:

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:

那是来自gnuplot的,它没有使用tex-font.我想使用matplotlib,将其呈现在tex中,但10 ^ {-n}中的减号应更短.有可能吗?

That one is from gnuplot, and it's not using the tex-font. I would like to use matplotlib, have it rendered in tex, but the minus signs in 10^{-n} should be shorter. Is that possible?

推荐答案

Dietrich给了您一个很好的答案,但是如果您想保留LogFormatter的所有功能(非基10,非整数指数) ,那么您可以创建自己的格式化程序:

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:

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,则可以这样做.

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. Of course, if you invent some creative LaTex with \scalebox or something equivalent, you may do so.

此:

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

创建:

此解决方案的优点在于,它会尽可能最小地更改输出.

The good thing about this solution is that it changes the output as minimally as possible.

这篇关于Matplotlib对数刻度刻度标签,乳胶字体中的减号太长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆