首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Matplotlib日志刻度滴答标签,在乳胶字体中减号太长

Matplotlib日志刻度滴答标签,在乳胶字体中减号太长
EN

Stack Overflow用户
提问于 2014-08-08 11:26:46
回答 2查看 2.4K关注 0票数 1

我使用的是“text.usetex”:在matplotib中是正确的。这对于线性尺度的情节来说是很好的。然而,对于一个日志规模,y-蜱看起来如下:

指数中的负号在一幅图中占用了大量的水平空间,这不是很好。我想让它看起来像这样:

那个是gnuplot的,它没有使用tex字体。我想使用matplotlib,让它在tex中呈现,但是10^{-n}中的减号应该更短。这有可能吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-08 14:37:30

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

代码语言:javascript
运行
AI代码解释
复制
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代码改为其他的东西。当然,如果您使用LaTex或类似的东西发明了一些创造性的\scalebox,您可以这样做。

这是:

代码语言:javascript
运行
AI代码解释
复制
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")

创建:

这个解决方案的好处是它尽可能少地改变输出。

票数 2
EN

Stack Overflow用户

发布于 2014-08-08 12:45:24

减号的长度是由您的LaTeX字体决定的--在数学模式下,二进制和一元小数具有相同的长度。根据this answer,你可以自己制作标签。试试这个:

代码语言:javascript
运行
AI代码解释
复制
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()

获得:

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25210898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档