我在matplotib中使用了'text.usetex': True。这对于线性比例尺的图表很好用。但是对于对数比例尺,y轴刻度看起来像这样:
指数中的减号占用了很多水平空间,这不太好看。我想让它看起来更像这样:
那个来自gnuplot,它没有使用tex-font。我想使用matplotlib,在tex中呈现它,但是10^{-n}中的减号应该更短。这可能吗?
![](https://istack.dev59.com/0kFxy.webp)
![](https://istack.dev59.com/Vk5tN.webp)
减号的长度取决于您的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()
获取:
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
\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")
创建:
这个解决方案的好处是尽可能地最小化了输出的变化。