Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: no effect of set_data in imshow for the plot

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.

like image 297
ahelm Avatar asked Jun 10 '12 16:06

ahelm


People also ask

What is CMAP in Imshow?

cmap : This parameter is a colormap instance or registered colormap name. norm : This parameter is the Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors. vmin, vmax : These parameter are optional in nature and they are colorbar range.

What is matplotlib use (' AGG ')?

The last, Agg, is a non-interactive backend that can only write to files. It is used on Linux, if Matplotlib cannot connect to either an X display or a Wayland display.

How do I ignore warnings in matplotlib?

Plot x and y using plot() method. Use warnings. filterwarnings("ignore") to suppress the warning. To display the figure, use show() method.

Does Imshow normalize?

By default, imshow normalizes the data to its min and max. You can control this with either the vmin and vmax arguments or with the norm argument (if you want a non-linear scaling).


1 Answers

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)
like image 121
Redoubts Avatar answered Sep 18 '22 08:09

Redoubts