Animating 3D scatter plot using Python mplotlib via serial data - python

I am trying to animate a 3D scatter plot using mplotlib in Python. I am able to graph the data and redraw every time, but this results in a frame rate of less than 1 FPS, and I need to scale to upwards of 30 FPS. When I run my code:
import serial
import numpy
import matplotlib.pyplot as plt #import matplotlib library
from mpl_toolkits.mplot3d import Axes3D
from drawnow import *
import matplotlib.animation
import time
ser = serial.Serial('COM7',9600,timeout=5)
ser.flushInput()
time.sleep(5)
ser.write(bytes(b's1000'))
x=list()
y=list()
z=list()
#plt.ion()
fig = plt.figure(figsize=(16,12))
ax = fig.add_subplot(111, projection="3d")
graph = ax.scatter(x,y,z, c='r',marker='o')
ax.set_xlim3d(-255, 255)
ax.set_ylim3d(-255, 255)
ax.set_zlim3d(-255, 255)
def generate():
while True:
try:
ser_bytes = ser.readline()
data = str(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
xyz = data.split(", ")
dx = float(xyz[0])
dy = float(xyz[1])
dz = float(xyz[2].replace(";",""))
x.append(dx);
y.append(dy);
z.append(dz);
graph._offset3d(x,y,z, c='r',marker='o')
except:
print("Keyboard Interrupt")
ser.close()
break
return graph,
ani = matplotlib.animation.FuncAnimation(fig, generate(), interval=1, blit=True)
plt.show()
I get the following error:
Traceback (most recent call last):
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
proxy(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
return mtd(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1026, in _start
self._init_draw()
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1750, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1772, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'tuple' object is not callable
Traceback (most recent call last):
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
proxy(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
return mtd(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1308, in _handle_resize
self._init_draw()
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1750, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1772, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'tuple' object is not callable
I am receiving x, y, z coordinates from a lidar module connected to an Arduino, which sends the coordinates over serial to the Python script.

A possible problem with your code is that the animation function (generate) is not supposed to run in an infinite loop. Furthermore, you are supposed to pass a reference to that function to FuncAnimate, but instead you are calling the function (i.e. you need to omit the parentheses in FuncAnimation(..., generate, ...)
The second problem is that you are treating graph._offset3d as if it was a function, when it is merely a tuple of lists. You should assign a new tuple to it, instead of trying to call the function (which I believe is what the error message alludes to).
I simplified your code and the following works fine:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
def update_lines(num):
dx, dy, dz = np.random.random((3,)) * 255 * 2 - 255 # replace this line with code to get data from serial line
text.set_text("{:d}: [{:.0f},{:.0f},{:.0f}]".format(num, dx, dy, dz)) # for debugging
x.append(dx)
y.append(dy)
z.append(dz)
graph._offsets3d = (x, y, z)
return graph,
x = [0]
y = [0]
z = [0]
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, projection="3d")
graph = ax.scatter(x, y, z, color='orange')
text = fig.text(0, 1, "TEXT", va='top') # for debugging
ax.set_xlim3d(-255, 255)
ax.set_ylim3d(-255, 255)
ax.set_zlim3d(-255, 255)
# Creating the Animation object
ani = animation.FuncAnimation(fig, update_lines, frames=200, interval=50, blit=False)
plt.show()

Related

How to animate a rectangle on a polar plot in Matplotlib

I have been trying to animate a polar plot in which I have a one degree wide wedge sweep all the way around the plot in a circle. I tried using the code below, but for some reason, it gives me the error AttributeError: 'NoneType' object has no attribute 'canvas'. I was trying to initialize the wedge as a rectangle patch that starts off on the right side of the plot and increases in x (angle), so I thought I should update the x-coordinate in the animate function, but for some reason, whenever I return patch (the rectangle) from animation, it gives me an error. Any tips? Thanks!
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import Rectangle
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
_, rlim = ax.get_ylim()
patch = Rectangle((0,0), np.radians(1), rlim)
def init():
ax.add_patch(patch)
return patch,
def animate(i):
patch.set_xy((np.radians(i), 0))
return patch,
ani = animation.FuncAnimation(fig, animate, frames=360, interval=30, blit=True)
plt.show()
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/usr/lib64/python3.6/tkinter/__init__.py", line 749, in callit
func(*args)
File "/usr/lib64/python3.6/site-packages/matplotlib/backends/_backend_tk.py", line 114, in _on_timer
TimerBase._on_timer(self)
File "/usr/lib64/python3.6/site-packages/matplotlib/backend_bases.py", line 1187, in _on_timer
ret = func(*args, **kwargs)
File "/usr/lib64/python3.6/site-packages/matplotlib/animation.py", line 1449, in _step
still_going = Animation._step(self, *args)
File "/usr/lib64/python3.6/site-packages/matplotlib/animation.py", line 1169, in _step
self._draw_next_frame(framedata, self._blit)
File "/usr/lib64/python3.6/site-packages/matplotlib/animation.py", line 1189, in _draw_next_frame
self._post_draw(framedata, blit)
File "/usr/lib64/python3.6/site-packages/matplotlib/animation.py", line 1212, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "/usr/lib64/python3.6/site-packages/matplotlib/animation.py", line 1229, in _blit_draw
bg_cache[a.axes] = a.figure.canvas.copy_from_bbox(a.axes.bbox)
AttributeError: 'NoneType' object has no attribute 'canvas'

edgecolors='None' causes error on animated 3d scatterplot

I'm trying to make a 3d scatterplot with fading points over time, similar to this question. However, when I apply the colormap to the data, then the face of the marker changes color but the edge remains solid.
I've tried using the edgecolors='None', edgecolor='none' kwargs, the marker='o' kwarg as per this example, and the edgecolor='face' kwarg. I've also tried using post creation methods such as scat3D.set_edgecolor("None") etc. The first attempts throw an error, and the latter have no effect.
Error from setting kwargs:
Traceback (most recent call last):
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 230, in saving
yield self
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1156, in save
writer.grab_frame(**savefig_kwargs)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 384, in grab_frame
dpi=self.dpi, **savefig_kwargs)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/figure.py", line 2180, in savefig
self.canvas.print_figure(fname, **kwargs)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/backends/backend_qt5agg.py", line 88, in print_figure
super().print_figure(*args, **kwargs)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 2082, in print_figure
**kwargs)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 442, in print_raw
FigureCanvasAgg.draw(self)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 388, in draw
self.figure.draw(self.renderer)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/figure.py", line 1709, in draw
renderer, self, artists, self.suppressComposite)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/image.py", line 135, in _draw_list_compositing_images
a.draw(renderer)
File "/home/max/.local/lib/python3.6/site-packages/matplotlib/artist.py", line 38, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/home/max/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 292, in draw
reverse=True)):
File "/home/max/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 291, in <lambda>
key=lambda col: col.do_3d_projection(renderer),
File "/home/max/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py", line 545, in do_3d_projection
ecs = (_zalpha(self._edgecolor3d, vzs) if self._depthshade else
File "/home/max/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py", line 847, in _zalpha
rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4))
File "<__array_function__ internals>", line 6, in broadcast_to
File "/home/max/.local/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 182, in broadcast_to
return _broadcast_to(array, shape, subok=subok, readonly=True)
File "/home/max/.local/lib/python3.6/site-packages/numpy/lib/stride_tricks.py", line 127, in _broadcast_to
op_flags=['readonly'], itershape=shape, order='C')
ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (0,4) and requested shape (100,4)
(There's a during the handling the above exception another occured error after that, but my post was flagged as spam so I didn't include it)
Here's the code without the error (adding a kwarg listed above causes the error):
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as mpatches
total = 10
num_whatever = 100
to_plot = [np.random.rand(num_whatever, 3) for i in range(total)]
colors = np.linspace(0, 1, num_whatever)
fig = plt.figure()
ax3d = Axes3D(fig)
scat3D = ax3d.scatter([],[],[], s=10, cmap="Blues", vmin=0, vmax=1)
scat3D.set_cmap("Blues") # cmap argument above is ignored, so set it manually
ttl = ax3d.text2D(0.05, 0.95, "", transform=ax3d.transAxes)
def update_plot(i):
print( i, to_plot[i].shape)
ttl.set_text('PCA on 3 components at step = {}'.format(i*20))
scat3D._offsets3d = np.transpose(to_plot[i])
scat3D.set_array(colors)
return scat3D,
def init():
scat3D.set_offsets([[],[],[]])
plt.style.use('ggplot')
ani = animation.FuncAnimation(fig, update_plot, init_func=init,
blit=False, interval=300, frames=range(total))
ani.save("ani.gif", writer="imagemagick")
plt.show()
Here's the plot with the marker edges not hidden:
Plot
You can see that the faded points still have the marker edges not colormapped. I would expect that setting edgecolor would be unnecessary in the first place, since the 2d animation clearly doesn't need it. But why would adding that kwarg cause me to get a operands could not be broadcast togeather error? I don't have any array with shape (0, 4), so it's not clear where this is coming from.
The problem is that if c (as the color argument) is not specified, it is not a priori clear if a colormapping should happen or not. This leads to some internal confusion about which arguments to obey to. But we can specify c as an empty list to get around that.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
total = 10
num_whatever = 100
to_plot = [np.random.rand(num_whatever, 3) for i in range(total)]
colors = np.linspace(0, 1, num_whatever)
fig = plt.figure()
ax3d = Axes3D(fig)
scat3D = ax3d.scatter([], [], [], s=10, c=[], cmap="Blues", vmin=0, vmax=1,
depthshade=False)
ttl = ax3d.text2D(0.05, 0.95, "", transform=ax3d.transAxes)
def update_plot(i):
print( i, to_plot[i].shape)
ttl.set_text('PCA on 3 components at step = {}'.format(i*20))
scat3D._offsets3d = np.transpose(to_plot[i])
scat3D.set_array(colors)
return scat3D,
def init():
scat3D.set_offsets([[],[],[]])
plt.style.use('ggplot')
ani = animation.FuncAnimation(fig, update_plot, init_func=init,
blit=False, interval=300, frames=range(total))
ani.save("ani.gif", writer="imagemagick")
plt.show()

Matplotlib animation - tuple object is not callable

having issues with the FuncAnimantion function in matplotlib. Code is as follows:
import time
from matplotlib import pyplot as plt
from matplotlib import animation
from ppbase import *
plt.ion()
#This is just essentially a stream of data
Paramater = PbaProObject("address of object")
fig = plt.figure()
ax = plt.axes(xlim=(0,2), ylim=(-90, 90))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(Parameter):
x = time.time()
y = Parameter.ValueStr
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate(Parameter), init_func=init,
frames=200, interval=2, blit=True)
plt.show()
And the error is:
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\matplotlib\backend_bases.py", line 1203, in _on_timer
ret = func(*args, **kwargs)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 876, in _step
still_going = Animation._step(self, *args)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 735, in _step self._draw_frame(framedata)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 754, in _draw_next_frame self._draw_frame(framedata, self._blit)
File "C:\Anaconda\lib\site-packages\matplotlib\animation.py", line 1049, in _draw_frame self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'tuple' object is not callable
Been reading around all morning and it seems commonly plt.plot is overwritten by a tuple, so I checked for that but don't think I have done it anywhere. I've also turned blit to false but that didn't help either. I do also want to interactively update the x-axis, I had line:
ax = plt.axes(xlim((x-10), (x+10)), ylim=(-90, 90))
in the animate function but took that out to see if it made any difference.
I think mostly the problems stem from not really understanding tuples too well. Also my understanding of the FuncAnimation function is that it calls the animate() each time it updates the plot - hence why I though that I could use it to update the axis' also. But this may not be the case.
Any help appreciated.
You need to pass in the function object not the result of the calling the function and you can pass a generator to frames (this might only work on 1.4.0+).
# turn your Parameter object into a generator
def param_gen(p):
yield p.ValueStr
def animate(p):
# get the data the is currently on the graph
old_x = line.get_xdata()
old_y = line.get_ydata()
# add the new data to the end of the old data
x = np.r_[old_x, time.time()]
y = np.r_[old_y, p]
# update the data in the line
line.set_data(x, y)
# return the line2D object so the blitting code knows what to redraw
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=param_gen(Parameter), interval=2, blit=True)
I also fixed a problem with your animation function and you should use 4 space indents, not 2.

Gracefully stopping (not pausing) an animated plot in python (matplotlib)

I am running an animated scatter in a process. Everything is working fine, except that an exception is throw when I want to exit everything.
import multiprocessing as mp
import time
from collections import deque
def start_colored_scores(nb_channels):
q = mp.Queue()
process = mp.Process(target=colored_scores,args=(q,nb_channels,4000))
process.start()
return process,q
def colored_scores(q,nb_channels,size):
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, axes = plt.subplots(nrows=nb_channels,ncols=1,sharex=True,sharey=True)
plt.axis([-1.0,1.0,-1.0,1.0])
scats = [axe.scatter([0], [0], c="white", s=size) for axe in axes]
def animate(i):
scores = q.get()
if scores is None : # this is the external signal saying things should stop
plt.close()
return [axe.scatter([0], [0], c="white", s=size) for axe in axes]
scats = []
for score,axe in zip(scores,axes):
score = max(min(1,1-score),0)
scats.append(axe.scatter([0], [0], c=(1-score,0,score), s=size))
return scats
ani = animation.FuncAnimation(fig, animate, interval=1, blit=True)
plt.show()
For example, this is working fine:
_,q = start_colored_scores(2)
x = 0
right = 1
time_start = time.time()
while time.time()-time_start < 5:
if right==1 and x>1.0:
x = 1.0
right = -1
if right==-1 and x<0.0:
x = 0.0
right = 1
x+=right*0.02
q.put([x,1-x])
time.sleep(0.02)
q.put(None) # indicating I do not need plotting anymore
print "this is printed ... exception in the process ?"
The behavior is as I expect : scatters are displayed and animated for 5 seconds, then the program continues. The only issue is that an exception is thrown (I guess in the process) saying :
AttributeError: 'NoneType' object has no attribute 'tk'
Is there a way to do the exact same thing but avoiding the exception ? Or to catch this exception somewhere ?
You can catch that exception pretty easily:
def colored_scores(q,nb_channels,size):
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, axes = plt.subplots(nrows=nb_channels,ncols=1,sharex=True,sharey=True)
plt.axis([-1.0,1.0,-1.0,1.0])
scats = [axe.scatter([0], [0], c="white", s=size) for axe in axes]
def animate(i):
scores = q.get()
if scores is None : # this is the external signal saying things should stop
plt.close()
return [axe.scatter([0], [0], c="white", s=size) for axe in axes]
scats = []
for score,axe in zip(scores,axes):
score = max(min(1,1-score),0)
scats.append(axe.scatter([0], [0], c=(1-score,0,score), s=size))
return scats
ani = animation.FuncAnimation(fig, animate, interval=1, blit=True)
try:
plt.show()
except AttributeError: # This will supress the exception
pass
However, once you get catch that one, you get a new one (at least on my system):
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 536, in callit
func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 141, in _on_timer
TimerBase._on_timer(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1203, in _on_timer
ret = func(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 876, in _step
still_going = Animation._step(self, *args)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 735, in _step
self._draw_next_frame(framedata, self._blit)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 755, in _draw_next_frame
self._post_draw(framedata, blit)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 778, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 798, in _blit_draw
ax.figure.canvas.blit(ax.bbox)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 353, in blit
tkagg.blit(self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/tkagg.py", line 20, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
TclError: this isn't a Tk application
I can't find any way to supress that one. What you could do, is just terminate the subprocess, rather than try to send it a signal to shutdown:
proc,q = start_colored_scores(2)
x = 0
right = 1
time_start = time.time()
while time.time()-time_start < 5:
if right==1 and x>1.0:
x = 1.0
right = -1
if right==-1 and x<0.0:
x = 0.0
right = 1
x+=right*0.02
q.put([x,1-x])
time.sleep(0.02)
#q.put(None) # indicating I do not need plotting anymore
proc.terminate()
This is not as graceful as sending something through the queue (and doesn't allow for any additional clean-up in the sub-process, assuming you want it), but doesn't throw any exceptions.

Matplotlib ArtistAnimation gives TypeError: 'AxesImage' object is not iterable [duplicate]

This question already has answers here:
matplotlib imshow(): how to animate?
(2 answers)
Closed 6 years ago.
Can you please help me figuring out what the problem is here? I don't know what is going wrong. Single plots from img can be plotted just fine, but the animation module gives an error. The Traceback says:
Traceback (most recent call last):
File "/home/ckropla/workspace/TAMM/Sandkasten.py", line 33, in <module>
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 818, in __init__
TimedAnimation.__init__(self, fig, *args, **kwargs)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 762, in __init__
*args, **kwargs)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 481, in __init__
self._init_draw()
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 824, in _init_draw
for artist in f:
TypeError: 'AxesImage' object is not iterable
Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def FUNCTION(p,r,t):
k_0,dx,c = p
x,y = r
z = np.exp(1j*(k_0[0]*np.meshgrid(x,y)[0]+k_0[1]*np.meshgrid(x,y)[1]-c*t))*np.exp(-((np.sqrt(np.meshgrid(x,y)[0]**2+np.meshgrid(x,y)[1]**2)-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4)
z = abs(z)
#k,F = FFT((x-c*t),y)
return(x,y,z)
#Parameter
N = 500
n = 20
x = np.linspace(-10,10,N)
y = np.linspace(-10,10,N)
t = np.linspace(0,30,n)
r=[x,y]
k_0 = [1,1]
dx = 1
c = 1
p = [k_0,dx,c]
fig = plt.figure("Moving Wavepackage")
Z = []
img = []
for i in range(n):
Z.append(FUNCTION(p,r,t[i])[2])
img.append(plt.imshow(Z[i]))
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
plt.show()
Each element in img needs to be a sequence of artists, not a single artist. If you change img.append(plt.imshow(Z[i])) to img.append([plt.imshow(Z[i])]) then your code works fine.

Categories

Resources