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

2024-06-28 05:54:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图制作4个子块(2x2)与倒y轴,同时也共享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))

enter image description here

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


Tags: importnumpytruematplotlibasnppltrandom
1条回答
网友
1楼 · 发布于 2024-06-28 05:54:53

因为您设置了sharey=True,所以这三个轴现在的行为就好像它们是一个轴一样。例如,当您反转其中一个选项时,将影响所有四个选项。问题在于,您正在一个for循环中反转轴,该循环的长度为4,因此您将所有轴反转偶数次。。。通过反转已经反转的轴,只需恢复其原始方向。尝试使用奇数个子块代替,您将看到轴已成功反转。

若要解决问题,应反转一个子块的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()

相关问题 更多 >