Reputation: 2019
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]
output:
True
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?
Upvotes: 2
Views: 152
Reputation: 339220
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()
I cannot well explain the problem, but is has to do with python lists.
Here, you are using
ims = [[None]*2]*4
which is not the same as
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.
Upvotes: 2