且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Matplotlib - imshow twiny() 问题

更新时间:2023-10-24 23:27:22

你误解了 twiny 的作用.它使完全独立 x 轴与共享 y 轴.

You're misunderstanding what twiny does. It makes a completely independent x-axis with a shared y-axis.

您想要做的是有一个带有链接轴的不同格式化程序(即共享轴限制,但没有其他内容).

What you want to do is have a different formatter with a linked axis (i.e. sharing the axis limits but nothing else).

执行此操作的简单方法是手动设置双联轴的轴限制:

The simple way to do this is to manually set the axis limits for the twinned axis:

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()

但是,一旦缩放或与图进行交互,您会注意到轴是未链接的.

However, as soon as you zoom or interact with the plot, you'll notice that the axes are unlinked.

您可以在共享 x 轴和 y 轴的相同位置添加一个轴,但随后也会共享刻度格式器.

You could add an axes in the same position with both shared x and y axes, but then the tick formatters are shared, as well.

因此,最简单的方法是使用寄生轴.

Therefore, the easiest way to do this is using a parasite axes.

作为一个简单的例子:

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()

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

Both this and the previous plot will look identical at first. The difference will become apparent when you interact (e.g. zoom/pan) with the plot.