Why does matplotlib.pyploy.imshow change its axis?

I try to build images in different subtitles, but for some reason, the axes of the images change when plotting. To demonstrate this, in the following example, I draw images in a 4 by 2 grid subnet, and I continue to check if the axes of the first image remain 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 shows that after the third image was built, the axes of the first image were changed:

 True True False False False False False False 

In addition, this turns out to be true:

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

output:

 True 

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

How is behavior explained and how can I get around it?

+2
source share
1 answer

Here is a workaround. You can create one list and add AxesImage objects to this 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() 

I cannot explain the problem, but is related to python lists.
Here you use

 ims = [[None]*2]*4 

which does not match

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

although both teams print the same list. Using the second approach will work for you.

+2
source

Source: https://habr.com/ru/post/1261922/


All Articles