Reputation: 702
I have a strange error which I can't fix without your help. After I set an image with imshow
in matplotlib it stays the same all the time even if I change it with the method set_data
. Just take a look on this example:
import numpy as np
from matplotlib import pyplot as plt
def newevent(event):
haha[1,1] += 1
img.set_data(haha)
print img.get_array() # the data is change at this point
plt.draw()
haha = np.zeros((2,2))
img = plt.imshow(haha)
print img.get_array() # [[0,0],[0,0]]
plt.connect('button_press_event', newevent)
plt.show()
After I plot it, the method set_data
doesn't change anything inside the plot. Can someone explain me why?
EDIT
Just added a few lines to point out what I actually want to do. I want to redraw the data after I press a mouse button. I don't want to delete the whole figure, because it would be stupid if only one thing changes.
Upvotes: 16
Views: 19489
Reputation: 843
The problem is because you have not updated the pixel scaling after the first call.
When you instantiate imshow
, it sets vmin
and vmax
from the initial data, and never touches it again. In your code, it sets both vmin
and vmax
to 0, since your data, haha = zeros((2,2))
, is zero everywhere.
Your new event should include autoscaling with img.autoscale()
, or explicitly set new scaling terms by setting img.norm.vmin/vmax
to something you prefer.
The function to set the new vmin
and vmax
is:
img.set_clim(vmin=new_vim, vmax=new_vmax)
Upvotes: 25
Reputation: 143032
Does this give you the output you expect?
import numpy as np
from matplotlib import pyplot as plt
haha = np.zeros((2,2))
img = plt.imshow(haha)
print img.get_array() # [[0,0],[0,0]]
haha[1,1] += 1
img.set_data(haha)
img = plt.imshow(haha) # <<------- added this line
print img.get_array() # [[0,0],[0,1]]
plt.show()
When I display the plot twice (once before the change to haha
, and at the end), it does change.
Upvotes: 3