为什么 matplotlib.pyploy.imshow 改变它的轴? [英] Why does matplotlib.pyploy.imshow change it axes?

查看:23
本文介绍了为什么 matplotlib.pyploy.imshow 改变它的轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在不同的子图中绘制图像,但由于某种原因,图像的轴在绘制时会发生变化.为了证明这一点,在下面的示例中,我将图像绘制在4乘2的子图网格中,并不断检查第一张图像的轴是否保持不变:

I try to plot images in different subplots, but for some reason the images' axes changes while plotting. To demonstrate this, in the following example I plot the images in a 4-by-2 grid of subplots, and I keep checking whether the axes of the first image stays the same:

import matplotlib.pyplot as plt
import numpy as np
_,ax = plt.subplots(4,2)
ims = [[None]*2]*4
for i in range(4):
     for j in range(2):
         plt.sca(ax[i][j])
         ims[i][j] = plt.imshow(np.random.rand(10,10))
         print(ims[0][0].axes is ax[0][0])

输出表明在绘制第三张图像后,第一张图像的轴发生了变化:

The output indicates that after the third image was plotted, the axes of the first image was changed:

True
True
False
False
False
False
False
False

另外,事实证明这是真的:

Also, this turns out to be true:

ims[0][0].axes is ax[3][0]

输出:

True

之所以困扰我,是因为我想在以后的步骤中使用ims [0] [0] .set_data()更新图像,但是当我尝试这样做时,它们只会在 ax []轴上更新.3][0]

The reason this bothers me is that I want to update the images in future steps using ims[0][0].set_data(), but when I try to do that they only update in the axes ax[3][0]

如何解释行为,我该如何解决?

How is behavior explained, and how can I work around it?

推荐答案

这里有一个解决方法.您可以创建一个列表,然后将 AxesImage 对象附加到该列表.这可以按预期工作.

Here is a workaround. You can create a single list and append your AxesImage objects to that list. This works as expected.

import matplotlib.pyplot as plt
import numpy as np
_,ax = plt.subplots(4,2)
ims2=[]

for i in range(4):
     for j in range(2):
         im = ax[i][j].imshow(np.zeros(shape=(10,10)), vmin=0, vmax = 1)
         ims2.append(im)
         print(ims2[0].axes is ax[0][0])

for i in range(4):
     for j in range(2):   
         ims2[i*2+j].set_data(np.random.rand(10,10))

plt.show()

<小时>

我无法很好地解释这个问题,但这与 python 列表有关.
在这里,您正在使用


I cannot well explain the problem, but is has to do with python lists.
Here, you are using

ims = [[None]*2]*4

ims = [ [ None for j in range(2)] for i in range(4)]

尽管两个命令都打印相同的列表.使用第二种方法也将为您工作.

although both commands print the same list. Using the second approach will work for you as well.

这篇关于为什么 matplotlib.pyploy.imshow 改变它的轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆