在我的图中,辅助 x 轴用于显示某些数据的另一个变量的值。现在,原始轴已按对数缩放。不幸的是,孪生轴将刻度(和标签)放置在原始轴的线性刻度上,而不是按照对数刻度。如何克服这个问题?
这里的代码示例应该将孪生轴的刻度放在与原始轴相同的(绝对轴)位置:
def conv(x):
"""some conversion function"""
# ...
return x2
ax = plt.subplot(1,1,1)
ax.set_xscale('log')
# get the location of the ticks of ax
axlocs,axlabels = plt.xticks()
# twin axis and set limits as in ax
ax2 = ax.twiny()
ax2.set_xlim(ax.get_xlim())
#Set the ticks, should be set referring to the log scale of ax, but are set referring to the linear scale
ax2.set_xticks(axlocs)
# put the converted labels
ax2.set_xticklabels(map(conv,axlocs))
另一种方法是(刻度线不会设置在同一位置,但这并不重要):
from matplotlib.ticker import FuncFormatter
ax = plt.subplot(1,1,1)
ax.set_xscale('log')
ax2 = ax.twiny()
ax2.set_xlim(ax.get_xlim())
ax2.xaxis.set_major_formatter(FuncFormatter(lambda x,pos:conv(x)))
只要不使用对数刻度,这两种方法都可以正常工作。
也许有一个简单的解决办法。文档中是否有我遗漏的内容?
作为解决方法,我尝试获取 ax 的刻度的 ax.transAxes 坐标,并将刻度放在 ax2 中的同一位置。但不存在类似的东西
ax2.set_xticks(axlocs,transform=ax2.transAxes)
TypeError: set_xticks() got an unexpected keyword argument 'transform'