Axes.invert_axis() 不适用于 matplotlib 子图的 sharey=True

Axes.invert_axis() does not work with sharey=True for matplotlib subplots

我正在尝试制作 4 个具有倒置 y 轴的子图 (2x2),同时在子图之间共享 y 轴。这是我得到的:

import matplotlib.pyplot as plt
import numpy as np

fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)

for ax in AX.flatten():
    ax.invert_yaxis()
    ax.plot(range(10), np.random.random(10))

似乎 ax.invert_axis()sharey=True 时被忽略了。如果我设置 sharey=False 我会在所有子图中得到一个倒置的 y 轴,但显然 y 轴不再在子图中共享。我在这里做错了什么,这是一个错误,还是做这样的事情没有意义?

自从您设置 sharey=True 后,所有三个轴现在的行为就好像它们是一个轴一样。例如,当你反转其中一个时,你会影响所有四个。问题在于你在 for 循环中反转轴,该循环运行长度为四的迭代,因此你将所有轴反转偶数次......通过反转已经反转的轴,你只需恢复其原始方向即可。尝试使用奇数个子图,您会看到坐标轴已成功反转。

要解决您的问题,您应该反转一个子图的 y 轴(并且仅反转一次)。以下代码对我有用:

import matplotlib.pyplot as plt
import numpy as np

fig,AX = plt.subplots(2, 2, sharex=True, sharey=True)

## access upper left subplot and invert it    
AX[0,0].invert_yaxis()

for ax in AX.flatten():
    ax.plot(range(10), np.random.random(10))

plt.show()