2

I use matplotlib.animation to animate data in a 3D array named arr. I read data from a h5 file using h5py library and everything is OK. But when using animation, the colormap got stuck in first frame of the data range, and after some steps it shows unnormalized colors while plotting.

Here is my code:

import numpy as np
import h5py
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.cm as cm

f = h5py.File('ez.h5','r')
arr = f["ez"][:,:,:]
f.close()

fig = plt.figure()

i = 0
p = plt.imshow(arr[:,:,0], interpolation='bilinear', cmap=cm.RdYlGn)

def updatefig(*args):
    global i
    i += 1
    if (i==333):
        i = 0
    p.set_array(arr[:,:,i])
    plt.clim()
    return p,

ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
sodd
  • 12,482
  • 3
  • 54
  • 62
VahidG
  • 165
  • 1
  • 7

1 Answers1

6

I think you want to replace set_clim() with

p.autoscale()

With no arguments, set_clim() is a no-op.

That said, changing your color scale in the middle of an animations seems very misleading.

You should also use set_data instead of set_array (according to the docs).

tacaswell
  • 84,579
  • 22
  • 210
  • 199
  • @VahidG If it solved your problem can you accept it (the big gray checkbox on the left side of the answer)? It will mark the problem solved and give both of us reputation. – tacaswell May 20 '13 at 20:35
  • Thanks for your neat and helpful answer! It solved my problem. I thought autoscale()‌ just affects axis limits and has no effect on colormap, but I was wrong. why you prefer set_data to set_array‌ (I couldn't find any difference)? – VahidG May 20 '13 at 20:40
  • 1
    `set_array` will be depreciated at some point in the future. `set_array` in fact just calls `set_data` https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/image.py#L429 – tacaswell May 20 '13 at 20:52