Python Matplotlib-imshow twiny()问题
我试图在matplotlib imshow()绘图中有两个相互依赖的x轴。我有底部x轴作为半径的平方,我想要顶部作为半径。到目前为止,我已经尝试过:Python Matplotlib-imshow twiny()问题,python,matplotlib,Python,Matplotlib,我试图在matplotlib imshow()绘图中有两个相互依赖的x轴。我有底部x轴作为半径的平方,我想要顶部作为半径。到目前为止,我已经尝试过: ax8 = ax7.twiny() ax8._sharex = ax7 fmtr = FuncFormatter(lambda x,pos: np.sqrt(x) ) ax8.xaxis.set_major_formatter(fmtr) ax8.set_xlabel("Radius [m]") 其中ax7为y轴和底部x轴(或半径平方)。我没有得
ax8 = ax7.twiny()
ax8._sharex = ax7
fmtr = FuncFormatter(lambda x,pos: np.sqrt(x) )
ax8.xaxis.set_major_formatter(fmtr)
ax8.set_xlabel("Radius [m]")
其中ax7为y轴和底部x轴(或半径平方)。我没有得到sqrt(x_底部)作为顶部的刻度,而是得到了从0到1的范围。我怎样才能解决这个问题
事先非常感谢。您误解了twiny的功能。它使x轴与y轴完全独立 您要做的是使用具有链接轴的不同格式化程序(即共享轴限制,但不共享其他限制) 执行此操作的简单方法是手动设置孪生轴的轴限制:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
fig, ax1 = plt.subplots()
ax1.plot(range(10))
ax2 = ax1.twiny()
formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
ax2.xaxis.set_major_formatter(formatter)
ax2.set_xlim(ax1.get_xlim())
plt.show()
但是,只要缩放或与绘图交互,就会注意到轴已取消链接
您可以在共享x轴和y轴的相同位置添加轴,但记号格式设置器也将共享
因此,最简单的方法是使用寄生轴
举个简单的例子:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
fig = plt.figure()
ax1 = SubplotHost(fig, 1,1,1)
fig.add_subplot(ax1)
ax2 = ax1.twin()
ax1.plot(range(10))
formatter = FuncFormatter(lambda x, pos: '{:0.2f}'.format(np.sqrt(x)))
ax2.xaxis.set_major_formatter(formatter)
plt.show()
这幅图和上一幅图一开始看起来是一样的。当您与绘图交互(例如缩放/平移)时,差异将变得明显。执行
ax2=ax1.twiny()
然后ax2.set_xbound(ax1.get_xbound())
缩放事件似乎没有传递到twiny的共享轴,因此如果存在共享轴+1的子批次,则设置绑定没有帮助,这是唯一有效的解决方案,设置bound是一个糟糕的黑客行为。