matplotlib 图像网格:invert_y轴不工作

ifsvaxew  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(285)

如何反转ImageGrid绘图网格中的Y轴?
这是我当前的测试代码:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, [im1, im2, im3, im4]):
    # Iterating over the grid returns the Axes.
    # ax.imshow(im)
    ax.pcolormesh(im)
    ax.invert_yaxis() # This seems to have no effect.

plt.show()

ax.invert_yaxis()不起作用,我总是得到增加的Y值,如下图所示:

m1m5dgzv

m1m5dgzv1#

好的,问题是ax.invert_yaxis()切换Y轴方向而不是仅仅设置它。因为我循环了偶数次,所以它没有效果。
以下是两种可能的解决方案:
1.使用ax.yaxis.set_inverted(True) . Cf:set_inverted
1.仅对每行中的一个图反转Y轴:

if idx in [0,2]:
  ax.invert_yaxis()
idx+=1

工作示例代码:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im1 = np.arange(100).reshape((10, 10))
im2 = im1.T
im3 = np.flipud(im1)
im4 = np.fliplr(im2)

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

idx=0
for ax, im in zip(grid, [im1, im2, im3, im4]):
    # Iterating over the grid returns the Axes.
    # ax.imshow(im)
    ax.pcolormesh(im)
    # ax.invert_yaxis()
    
    # Directly setting the axis direction, rather than toggling it.
    ax.yaxis.set_inverted(True)
    
    # Alternative method:
    # if idx in [0,2]:
    #   ax.invert_yaxis()
    # idx+=1
    
plt.show()

相关问题