Matplotlib - imshow twiny()问题

时间:2012-12-07 23:31:01

标签: 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轴(或半径平方)。而不是将sqrt(x_bottom)作为顶部的刻度,我只得到0到1的范围。我该如何解决这个问题?

提前多多感谢。

1 个答案:

答案 0 :(得分:4)

你误解了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()

enter image description here

但是,只要缩放或与绘图交互,您就会注意到轴是未链接的。

您可以使用共享的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()

这个和之前的情节一开始看起来都是一样的。当您与绘图进行交互(例如缩放/平移)时,差异将变得明显。

相关问题