Matplotlib - imshow twiny() 问题

mad*_*ast 3 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]")
Run Code Online (Sandbox Code Playgroud)

其中 ax7 是 y 轴和底部 x 轴(或半径平方)。我没有得到 sqrt (x_bottom) 作为顶部的刻度,而是得到了从 0 到 1 的范围。我该如何解决这个问题?

预先非常感谢。

Joe*_*ton 5

你误解了它的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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

您可以在同一位置添加一个共享 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()
Run Code Online (Sandbox Code Playgroud)

该图和前一个图乍一看看起来是一样的。当您与绘图交互(例如缩放/平移)时,差异将变得明显。