我在使用matplotlib(版本3.1.3)时遇到了麻烦:我想在保留科学计数法的同时在对数刻度轴上添加自定义刻度和刻度标签。
换句话说,我想在对数刻度轴上添加自定义刻度,并使用老式的'%1.1e'(或任何数字)格式标记它们,例如,而不是使用'2.5e -02”,我想使用“ 2.5 x 10 ^ -2”(或乳胶中的“ 2.5 \ times 10 ^ {-2}”)。
因此,我从没有自定义刻度的最低限度的代码开始:
import matplotlib as mpl
import matplotlib.pyplot as plt
print('MATPLOTLIB VERSION : %s' % mpl.__version__)
plt.style.use("default")
# DATA
x = [0.1,0.075,0.05,0.025,0.01,0.0075,0.005,0.0025,0.001,0.00075,0.0005,0.00025,0.0001,7.5e-05,5e-05,2.5e-05,1e-05,1e-06,1e-07,1e-08,1e-09,1e-10]
y = x
fig = plt.figure()
ax = plt.axes()
plt.loglog()
plt.minorticks_off()
path = ax.plot(x,y)
plt.savefig('test.png')
给出:
很好,但是正如我所说,我想在xaxis上添加自定义刻度。更准确地说,我想对轴设置限制,并在这些限制之间定义对数分隔的标签。假设我要4个滴答声;它提供了以下代码:
import matplotlib as mpl
import matplotlib.pyplot as plt
print('MATPLOTLIB VERSION : %s' % mpl.__version__)
plt.style.use("default")
# DATA
x = [0.1,1e-10]
y = x
xmin = min(x)
xmax = max(x)
ymin = min(y)
ymax = max(y)
# XTICKS
nbdiv = 4
xTicks = []
k = pow((xmin/xmax),1./(nbdiv-1.))
for i in range(0,nbdiv):
xTicks.append(xmax*pow(k,i))
# PLOT
fig = plt.figure()
ax = plt.axes()
plt.loglog()
plt.minorticks_off()
plt.axis([xmin,xmax,ymin,ymax])
plt.xticks(xTicks)
path = ax.plot(x,y)
plt.savefig('test_working_4.png')
其提供以下图表:
这就是我想要获得的结果。但是,如果刻度数(nbdiv)发生变化,例如变为等于5,我得到:
这一次只标记了第一和最后一个刻度。似乎只标记了等于(或至少接近)十的整数次幂的数字(10 ^ n)。我尝试使用matplot.ticker.ScalarFormatter更改默认的刻度格式,但是我没有设法对其进行调整以解决此问题。我还尝试了LogFormatterMathText和LogFormatterSciNotation,这并不好。
对于我来说,这个问题本身似乎并不那么困难,所以我不明白为什么我遇到了那么多麻烦……我在做什么错?有人有钥匙让我理解我的错误吗?
无论如何,我感谢您的阅读,并在此先感谢您的答复。
P.S .:对不起潜在的英语错误,这不是我的母语。