在我的图中,使用了一个次要的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'