(python) matplotlib animation doesn't show

2019-07-30 07:43发布

I wrote the following code based on the matplotlib site example.

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

fig = plt.figure()
nFreqs = 1024
nFFTWindows = 512
viewport = np.ones((nFreqs, nFFTWindows))
im = plt.imshow(viewport, animated=True)


def updatefig(*args):
    global viewport
    print viewport
    viewport = np.roll(viewport, -1, axis=1)
    viewport[:, -1] = 0
    im.set_array(viewport)
    return im,


ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()

Before changing the animation works, but now it doesn't. I expected it to start with a purple plot, which slowly turns yellow from the right edge to the left. The viewport variable does update correctly (checked it with print in my function).

I get the static image (all ones, like it was initially):

enter image description here

Where did I go wrong here?

3条回答
爷的心禁止访问
2楼-- · 2019-07-30 08:11

The imshow plot is initialized with one single value (1 in this case), so any value normalized to the range between 1 and 1 becomes the same color.

In order to change this, you may

  1. initiate the imshowplot with limits for the color (vmin=0, vmax=1).
  2. initiate the imshow plot with a normalization instance

    norm = matplotlib.colors.Normalize(vmin=0, vmax=1)
    im = plt.imshow(arr, norm=norm)
    
  3. Set the limits afterwards using im.set_clim(0,1).
查看更多
地球回转人心会变
3楼-- · 2019-07-30 08:12

The problem is you are defining a plot initially with a single colour (1.0) so the colour range is set to this. When you update the figure, the range of colours is 1.0 +- some small value so you don't see the change. You need to set the colour range to between one and zero with vmin/vmax arguments as follows:

im = plt.imshow(viewport, animated=True, vmin=0., vmax=1.)

The rest of the code stays the same and this should work as expected. Another alternative is to add the call,

im.autoscale()

after im.set_array(viewpoint) to force the colour range to be updated each time.

查看更多
不美不萌又怎样
4楼-- · 2019-07-30 08:16

Preferences > IPython Console > Graphics > Backend and change it from "Inline" to "Automatic"

Do not forget to restart you IDE (Spyder, PyCharm, etc.) after applying above change.

Cheers

:)

查看更多
登录 后发表回答