在我的绘图中,辅助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'
3条答案
按热度按时间y4ekin9u1#
刚才有人问过这个问题,但我还是被同样的问题绊倒了。
我最终设法通过引入对数比例(
semilogx
)透明(alpha=0
)虚拟图解决了这个问题。示例:
在上面的例子中,垂直线表明第一和第二轴确实按照需要相互移动。
x = 100
移动到z = 2*x**0.5 = 20
。颜色只是为了说明哪条垂直线与哪条轴相对应。xe55xuns2#
不需要盖住它们,只要消灭蜱虫!
zf9nrax13#
我想你可以通过拨打
ax2.set_xscale('log')
来解决你的问题。