我使用的是“text.usetex”:在matplotib中是正确的。这对于线性尺度的情节来说是很好的。然而,对于一个日志规模,y-蜱看起来如下:
指数中的负号在一幅图中占用了大量的水平空间,这不是很好。我想让它看起来像这样:
那个是gnuplot的,它没有使用tex字体。我想使用matplotlib,让它在tex中呈现,但是10^{-n}中的减号应该更短。这有可能吗?
发布于 2014-08-08 14:37:30
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
唯一真正做到的就是获取通常的格式化程序的输出,找出可能的负指数,并将数学的LaTeX代码改为其他的东西。当然,如果您使用LaTex或类似的东西发明了一些创造性的\scalebox
,您可以这样做。
这是:
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")
创建:
这个解决方案的好处是它尽可能少地改变输出。
发布于 2014-08-08 12:45:24
减号的长度是由您的LaTeX字体决定的--在数学模式下,二进制和一元小数具有相同的长度。根据this answer,你可以自己制作标签。试试这个:
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()
获得:
https://stackoverflow.com/questions/25210898
复制相似问题