这是出了什么问题
这是因为两个 x 尺度之间的映射是非线性的(指数/对数)。实际上,您有一个轴作为对数刻度,另一个轴作为正常刻度。根据您定义限制的方式,两者在端点处重合,但不在两者之间重合。下面演示了这个想法。 x2 的“映射值”相对于 x1 值绘制在 y 轴上。我标记为“仅限端点”的蓝线是您所期望的,但“全域”映射是现实中发生的情况。
import matplotlib.pyplot as plt
import numpy as np
# Endpoints only
x01 = np.array([5.2,5.8])
y01 = np.exp(x01)
# Full domain
x = np.linspace(5.2,5.8,100)
y = np.exp(x)
plt.plot(x01,y01,label='endpoints only')
plt.plot(x,y, label='full domain')
plt.legend()
plt.show()
这是一种解决方法
在对数刻度上实例化两个轴。在你的情况下你想要自然对数,所以我们通过basex=np.e
。然后,您需要手动指定两个轴上的刻度位置。在ax1
我们只使用预先指定的位置;为了ax2
您可以使用指定后生成的位置MultipleLocator
.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xscale('log', basex=np.e)
# Array of tick locations...use the true value (not log value)
locs = np.exp(np.array([5.2,5.3,5.4,5.5,5.6,5.7,5.8]))
ax1.set_xlabel(r'$ln(\sigma)$')
ax1.set_xlim([locs[0],locs[-1]])
ax1.set_xticks(locs)
ax1.set_xticklabels(np.log(locs))
ax2 = ax1.twiny()
ax2.set_xscale('log', basex=np.e)
ax2.set_xlabel(r'$\sigma$')
ax2.set_xlim((ax1.get_xlim()))
ax2.xaxis.set_major_locator(MultipleLocator(base=25))
# Manually set the tick labels to match the positions your set with the locator
ax2.set_xticklabels(['{:.0f}'.format(k) for k in ax2.get_xticks()])
ax1.plot(locs,locs*0+.4,'o')
ax2.plot(locs,locs*0+.6,'o',color='C1')
ax1.set_ylim([0,1])
plt.show()