imshow.set_data() not working for FuncAnimation - python

I am writing a program for 2D FDTD light propagation, in this code, when I run the program with ax.imshow() command in the animate function, the program works fine whereas when I use the im.set_data() command, it gives me a blank image. Can somebody please tell me what am I doing wrong? Also, can somebody tell me how to set the colormap at the beginning so that I dont have to update it during the animation loop. The point is I don't want the imshow() command to draw everything everytime the loop is run.
Thanks for all the help. I am learning programming please suggest me what to do.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
xdim = 100
ydim = 100
epsilon = np.ones([xdim,ydim])*8.854187817*10**(-12)
mu = np.ones([xdim,ydim])*4*np.pi*10**(-7)
c = 299792458
delta = 10**-6
deltat = delta/(c*(2**0.5))
Hz = np.zeros([xdim,ydim])
Ey = np.zeros([xdim,ydim])
Ex = np.zeros([xdim,ydim])
fig = plt.figure()
ax = plt.axes()
im = ax.imshow(Hz)
Hz[xdim/2,ydim/2]=1
def init():
im.set_data(np.zeros(Hz.shape))
return
def animate(n, *args, **kwargs):
Ex[0:xdim-1,0:ydim-1]=Ex[0:xdim-1,0:ydim-1]+(deltat/(delta*mu[0:xdim-1,0:ydim-1]))*(Hz[1:xdim,0:ydim-1]-Hz[0:xdim-1,0:ydim-1])
Ey[0:xdim-1,0:ydim-1]=Ey[0:xdim-1,0:ydim-1]-(deltat/(delta*mu[0:xdim-1,0:ydim-1]))*(Hz[0:xdim-1,1:ydim]-Hz[0:xdim-1,0:ydim-1])
Hz[1:xdim,1:ydim]=Hz[1:xdim,1:ydim]+(deltat/(delta*epsilon[1:xdim,1:ydim]))*(Ex[1:xdim,1:ydim]-Ex[0:xdim-1,1:ydim]-Ey[1:xdim,1:ydim]+Ey[1:xdim,0:ydim-1])
if(n==0):Hz[xdim/2,ydim/2]=0
#im.set_data(Hz)
ax.imshow(Hz) # Delete this command and try running the program with the above command.
return
ani = animation.FuncAnimation(fig, animate, init_func=init, frames = 200, interval = 10, blit = False, repeat = False)
fig.show()

Actually, your first version was working just fine also. The problem was that because im is initialized with an array of zeros, the vmin and vmax for the colorscale were both zero. Updates to im after that using set_data did not update vmin and vmax, whereas ax.imshow automatically rescales the color ranges. If you set the color ranges at the beginning to something reasonable, it works fine:
ax.imshow(Hz, vmin=-0.2, vmax=0.2)
That's the only thing you need to change from the code in the question to make it work (with im.set_data in the animation function).

I got the program to work by making a few changes, though i cannot understand why it is not working the way i wrote it in the question. Here is what i changed:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
xdim = 100
ydim = 100
epsilon = np.ones([xdim,ydim])*8.854187817*10**(-12)
mu = np.ones([xdim,ydim])*4*np.pi*10**(-7)
c = 299792458
delta = 10**-6
deltat = delta/(c*(2**0.5))
Hz = np.zeros([xdim,ydim])
Ey = np.zeros([xdim,ydim])
Ex = np.zeros([xdim,ydim])
Hz[xdim/2,ydim/2]=1
def init():
global fig, ax, im
fig = plt.figure()
ax = plt.axes()
im = ax.imshow(Hz, cmap="jet")
im.set_data(np.zeros(Hz.shape))
return
def animate(n):
Ex[0:xdim-1,0:ydim-1]=Ex[0:xdim-1,0:ydim-1]+(deltat/(delta*mu[0:xdim-1,0:ydim-1]))*(Hz[1:xdim,0:ydim-1]-Hz[0:xdim-1,0:ydim-1])
Ey[0:xdim-1,0:ydim-1]=Ey[0:xdim-1,0:ydim-1]-(deltat/(delta*mu[0:xdim-1,0:ydim-1]))*(Hz[0:xdim-1,1:ydim]-Hz[0:xdim-1,0:ydim-1])
Hz[1:xdim,1:ydim]=Hz[1:xdim,1:ydim]+(deltat/(delta*epsilon[1:xdim,1:ydim]))*(Ex[1:xdim,1:ydim]-Ex[0:xdim-1,1:ydim]-Ey[1:xdim,1:ydim]+Ey[1:xdim,0:ydim-1])
if(n==0):Hz[xdim/2,ydim/2]=0
im.set_data(Hz)
return
init()
ani = animation.FuncAnimation(fig, animate, frames = 500, interval = 10, blit = False, repeat = False)
fig.show()

Related

Matplotlib how to move axis along data in a real-time animation

I'm trying to plot data that is generated in runtime. In order to do so I'm using matplotlib.animation.FuncAnimation.
While the data is displayed correctly, the axis values are not updating accordingly to the values that are being displayed:
The x axis displays values from 0 to 10 eventhough I update them in every iteration in the update_line function (see code below).
DataSource contains the data vector and appends values at runtime, and also returns the indexes of the values being returned:
import numpy as np
class DataSource:
data = []
display = 10
# Append one random number and return last 10 values
def getData(self):
self.data.append(np.random.rand(1)[0])
if(len(self.data) <= self.display):
return self.data
else:
return self.data[-self.display:]
# Return the index of the last 10 values
def getIndexVector(self):
if(len(self.data) <= self.display):
return list(range(len(self.data)))
else:
return list(range(len(self.data)))[-self.display:]
I've obtained the plot_animation function from the matplotlib docs.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datasource import DataSource
def update_line(num, source, line):
data = source.getData()
indexs = source.getIndexVector()
if indexs[0] != 0:
plt.xlim(indexs[0], indexs[-1])
dim=np.arange(indexs[0],indexs[-1],1)
plt.xticks(dim)
line.set_data(indexs,data)
return line,
def plot_animation():
fig1 = plt.figure()
source = DataSource()
l, = plt.plot([], [], 'r-')
plt.xlim(0, 10)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
interval=150, blit=True)
# To save the animation, use the command: line_ani.save('lines.mp4')
plt.show()
if __name__ == "__main__":
plot_animation()
How can I update the x axis values in every iteration of the animation?
(I appreciate suggestions to improve the code if you see any mistakes, eventhough they might not be related to the question).
Here is a simple case of how you can achieve this.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
%matplotlib notebook
#data generator
data = np.random.random((100,))
#setup figure
fig = plt.figure(figsize=(5,4))
ax = fig.add_subplot(1,1,1)
#rolling window size
repeat_length = 25
ax.set_xlim([0,repeat_length])
ax.set_ylim([-2,2])
#set figure to be modified
im, = ax.plot([], [])
def func(n):
im.set_xdata(np.arange(n))
im.set_ydata(data[0:n])
if n>repeat_length:
lim = ax.set_xlim(n-repeat_length, n)
else:
lim = ax.set_xlim(0,repeat_length)
return im
ani = animation.FuncAnimation(fig, func, frames=data.shape[0], interval=30, blit=False)
plt.show()
#ani.save('animation.gif',writer='pillow', fps=30)
Solution
My problem was in the following line:
line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
interval=150, blit=True)
What I had to do is change the blit parameter to False and the x axis started to move as desired.

python matplotlib shared xlabel description / title on multiple subplots for animation

I'm using the following code to produce an animation with matplotlib that is intended to visualize my experiments.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation, PillowWriter
plt.rcParams['animation.html'] = 'jshtml'
def make_grid(X, description=None, labels=None, title_fmt="label: {}", cmap='gray', ncols=3, colors=None):
L = len(X)
nrows = -(-L // ncols)
frame_plot = []
for i in range(L):
plt.subplot(nrows, ncols, i + 1)
im = plt.imshow(X[i].squeeze(), cmap=cmap, interpolation='none')
if labels is not None:
color = 'k' if colors is None else colors[i]
plt.title(title_fmt.format(labels[i]), color=color)
plt.xticks([])
plt.yticks([])
frame_plot.append(im)
return frame_plot
def animate_step(X):
return X ** 2
n_splots = 6
X = np.random.random((n_splots,32,32,3))
Y = X
X_t = []
for i in range(10):
Y = animate_step(Y)
X_t.append((Y, i))
frames = []
for X, step in X_t:
frame = make_grid(X,
description="step={}".format(step),
labels=range(n_splots),
title_fmt="target: {}")
frames.append(frame)
anim = ArtistAnimation(plt.gcf(), frames,
interval=300, repeat_delay=8000, blit=True)
plt.close()
anim.save("test.gif", writer=PillowWriter())
anim
The result can be seen here:
https://i.stack.imgur.com/OaOsf.gif
It works fine so far, but I'm having trouble getting a shared xlabel to add a description for all of the 6 subplots in the animation. It is supposed to show what step the image is on, i.e. "step=5".
Since it is an animation, I cannot use xlabel or set_title (since it would be constant over the whole animation) and have to draw the text myself.
I've tried something along the lines of..
def make_grid(X, description=None, labels=None, title_fmt="label: {}", cmap='gray', ncols=3, colors=None):
L = len(X)
nrows = -(-L // ncols)
frame_plot = []
desc = plt.text(0.5, .04, description,
size=plt.rcparams["axes.titlesize"],
ha="center",
transform=plt.gca().transAxes
)
frame_plot.append(desc)
...
This, of course, won't work, because the axes are not yet created. I tried using the axis of another subplot(nrows, 1, nrows), but then the existing images are drawn over..
Does anyone have a solution to this?
Edit:
unclean, hacky solution for now:
Wait for the axes of the middle image of the last row to be created and use that for plotting the text.
In the for loop:
...
if i == int((nrows - 0.5) * ncols):
title = ax.text(0.25, -.3, description,
size=plt.rcParams["axes.titlesize"],
# ha="center",
transform=ax.transAxes
)
frame_plot.append(title)
...
To me, your case is easier to solve with FuncAnimation instead of ArtistAnimation, even if you already have access to the full list of data you want to show animated (see this thread for a discussion about the difference between the two functions).
Inspired from this FuncAnimation example, I wrote the code below that does what you needed (using the same code with ArtistAnimation and correct list of arguments does not work).
The main idea is to initialize all elements to be animated at the beginning, and to update them over the animation frames. This can be done for the text object (step_txt = fig.text(...)) in charge of displaying the current step, and for the images out from ax.imshow. You can then update whatever object you would like to see animated with this recipe.
Note that the technique works if you want the text to be an x_label or any text you choose to show. See the commented line in the code.
#!/Users/seydoux/anaconda3/envs/jupyter/bin/python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
# parameters
n_frames = 10
n_splots = 6
n_cols = 3
n_rows = n_splots // n_cols
def update_data(x):
return x ** 2
# create all snapshots
snapshots = [np.random.rand(n_splots, 32, 32, 3)]
for _ in range(n_frames):
snapshots.append(update_data(snapshots[-1]))
# initialize figure and static elements
fig, axes = plt.subplots(2, 3)
axes = axes.ravel() # so we can access all axes with a single index
for i, ax in enumerate(axes):
ax.set_xticks([])
ax.set_yticks([])
ax.set_title("target: {}".format(i))
# initialize elements to be animated
step_txt = fig.text(0.5, 0.95, "step: 0", ha="center", weight="bold")
# step_txt = axes[4].set_xlabel("step: 0") # also works with x_label
imgs = list()
for a, s in zip(axes, snapshots[0]):
imgs.append(a.imshow(s, interpolation="none", cmap="gray"))
# animation function
def animate(i):
# update images
for img, s in zip(imgs, snapshots[i]):
img.set_data(s)
# update text
step_txt.set_text("step: {}".format(i))
# etc
anim = FuncAnimation(fig, animate, frames=n_frames, interval=300)
anim.save("test.gif", writer=PillowWriter())
Here is the output I got from the above code:

Oscilloscope animation of an electric signal in Python

Good evening,
I am new to Python. I am trying to process a signal saved in a npy file.
This file contains an electrical signal that I want to view as I do in the laboratory with the oscilloscope, so I want to generate an animation that shows me how the signal changes over time.
Here is my attempt:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
signal = np.load('signal.npy')
fig = plt.figure()
def animation(i):
plt.cla()
plt.plot(signal)
# what to do here?
anim = FuncAnimation(fig, animation, frames = len(signal), interval = 10)
plt.show()
I have no idea what to do in the animation function.
Thanks in advance and sorry for my english
Since I do not have access to your signal data, I generate mine in order to run the animation. Replace my random signal with yours.
A basic code to view you signal with respect to time could be this:
# import
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# signal generation
N = 10001
stop = 100
time = np.linspace(0, stop, N)
A = 1/4*np.cos(2*np.pi*(np.abs(time - stop/2)/stop)) + 1
f = np.concatenate((1*np.ones(int(N/4)), 2*np.ones(int(N/2) + 1), 1*np.ones(int(N/4))))
signal = A * np.sin(2*np.pi*f*time) + 0.05*np.random.randn(N)
# figure preparation
fig, ax = plt.subplots(1, 1, figsize = (8*0.9, 6*0.9))
displayed_period = int(2*f.min())
span = int(N/stop/f.min())
def animation(i):
# delete previous frame
ax.cla()
# plot and set axes limits
ax.plot(time[span*i: 1 + span*(i + displayed_period)],
signal[span*i: 1 + span*(i + displayed_period)])
ax.set_xlim([time[span*i], time[span*(i + displayed_period)]])
ax.set_ylim([1.1*signal.min(), 1.1*signal.max()])
# run animation
anim = FuncAnimation(fig, animation, frames = int(len(time)/span - 1), interval = 10)
plt.show()
which gives this animation:
Explanation
In my case, the signal is a sine wave which changes amplitude and frequency over time (plus some noise). I choose to see two complete oscillations of my signal per each frame, so I set
displayed_period = int(2*f.min())
to be sure to see at least the two complete oscillations. Then I have to define the amount of time passed through x axis between a frame and the following, so I set:
span = int(N/stop/f.min())
That being said, when you run the code, the animation function is called multiple times, in each time the i counter increases by 1. So you can use this counter to slice the time and the signal arrays: time[span*i: 1 + span*(i + displayed_period)].
In this way you plot a displayed_period number of complete oscillations and, for each frame, you scroll the x axis by span element.
You have to set displayed_period and span according to your signal properties in order to get a similar result.
If you want a little bit customization like an oscilloscope, check this code:
# import
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# signal generation
N = 10001
stop = 100
time = np.linspace(0, stop, N)
A = 1/4*np.cos(2*np.pi*(np.abs(time - stop/2)/stop)) + 1
f = np.concatenate((1*np.ones(int(N/4)), 2*np.ones(int(N/2) + 1), 1*np.ones(int(N/4))))
signal = A * np.sin(2*np.pi*f*time) + 0.05*np.random.randn(N)
# color definition
black = '#0F110D'
grey = '#3B3D3A'
yellow = '#FFFF21'
# figure preparation
fig, ax = plt.subplots(1, 1, figsize = (8*0.9, 6*0.9))
displayed_period = int(2*f.min())
span = int(N/stop/f.min())
def animation(i):
# delete previous frame
ax.cla()
# set background color and plot
ax.set_facecolor(black)
ax.plot(time[span*i: 1 + span*(i + displayed_period)],
signal[span*i: 1 + span*(i + displayed_period)],
color = yellow)
# plot axes lines
ax.hlines(y = 0,
xmin = 0,
xmax = stop,
lw = 2,
colors = grey)
ax.vlines(x = time[int(span*i + (1 + span*displayed_period)/2)],
ymin = 1.1*signal.min(),
ymax = 1.1*signal.max(),
lw = 2,
colors = grey)
# set grid, axes limits and ticks
ax.grid(which = 'major',
ls = '-',
lw = 0.5,
color = grey)
ax.set_xlim([time[span*i], time[span*(i + displayed_period)]])
ax.set_ylim([1.1*signal.min(), 1.1*signal.max()])
plt.tick_params(axis = 'both',
which = 'both',
bottom = False,
left = False,
labelbottom = False,
labelleft = False)
# run animation
anim = FuncAnimation(fig, animation, frames = int(len(time)/span - 1), interval = 10)
anim.save('oscilloscope.gif', writer = 'imagemagick')
plt.show()
I do not changed the functionalities, only the aspect of the animation:
In the matplotlib documentation you can see an example of a simulation of an oscilloscope here

How to move figure window in interactive mode in matplotlib?

I'm trying to monitor real-time data with matplotlib.
I found that I can update plot dynamically with interactive mode in Pyplot.
And it worked well, but one problem is 'I cannot manipulate the figure window at all'. For example, move or re-size the figure window.
Here is my code.
This is cons of interactive mode? or I'm using it incorrectly?
import matplotlib.pyplot as plt
import time
import math
# generate data
x = [0.1*_a for _a in range(1000)]
y = map(lambda x : math.sin(x), x)
# interactive mode
plt.ion() # identical plt.interactive(True)
fig, ax = plt.subplots()
# ax = plt.gca()
lines, = ax.plot([], [])
# ax.set_ylim(-1, 1)
ax.grid()
MAX_N_DATA = 100
x_data = []
y_data = []
for i in range(len(x)):
# New data received
x_data.append(x[i])
y_data.append(y[i])
# limit data length
if x_data.__len__() > MAX_N_DATA:
x_data.pop(0)
y_data.pop(0)
# Set Data
lines.set_xdata(x_data)
lines.set_ydata(y_data)
# The data limits are not updated automatically.
ax.relim()
# with tight True, graph flows smoothly.
ax.autoscale_view(tight=True, scalex=True, scaley=True)
# draw
plt.draw()
time.sleep(0.01)
Thank you.
As shown in this answer to another question, replace plt.draw() with plt.pause(0.05). This solved the problem for me.
Although I still think you should use bokeh, I'll tell you how to do it with matplotlib.
The problem why it won't work ist that matplotlib's event loop is not active and therefore it cannot digest window events (like close or resize). Unfortunately it is not possible to trigger this digestion from the outside. What you have to do is to use matplotlib's animation system.
Your code is actually quite well prepared for it so you can use FuncAnimation.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import math
# generate data
x = [0.1*_a for _a in range(1000)]
y = map(lambda x : math.sin(x), x)
# don't need ion, we're using block=True (see end of code)
fig, ax = plt.subplots()
fig.show()
# ax = plt.gca()
lines, = ax.plot([], [])
# ax.set_ylim(-1, 1)
ax.grid()
MAX_N_DATA = 100
x_data = []
y_data = []
def showdata(i):
# New data received
x_data.append(x[i])
y_data.append(y[i])
# limit data length
if x_data.__len__() > MAX_N_DATA:
x_data.pop(0)
y_data.pop(0)
# Set Data
lines.set_xdata(x_data)
lines.set_ydata(y_data)
# The data limits are not updated automatically.
ax.relim()
# with tight True, graph flows smoothly.
ax.autoscale_view(tight=True, scalex=True, scaley=True)
# draw will be called by the animation system
# instead of time.sleep(0.01) we use an update interval of 10ms
# which has the same effect
anim = FuncAnimation(fig, showdata, range(len(x)), interval=10, repeat=False)
# start eventloop
plt.show(block=True)

Animation of pcolormesh() with mpl_toolkit.basemap giving attribute error

I am trying to animate some density data on a basemap map. Following an approach as was done in [this SO question][1], I get the following error:
/usr/local/lib/python2.7/dist-packages/matplotlib/collections.pyc in update_scalarmappable(self)
627 if self._A is None:
628 return
--> 629 if self._A.ndim > 1:
630 raise ValueError('Collections can only map rank 1 arrays')
631 if not self.check_update("array"):
AttributeError: 'list' object has no attribute 'ndim'
If I instead set the data in init() with null values by self.quad.set_array(self.z.ravel()), I end up with two plotted maps with no data being animated.
Any light that anybody could shed on what I'm doing wrong would be greatly appreciated. Thanks!
example code:
def plot_pcolor(lons,lats):
class UpdateQuad(object):
def __init__(self,ax, map_object, lons, lats):
self.ax = ax
self.m = map_object
self.lons = lons
self.lats = lats
self.ydim, self.xdim = lons.shape
self.z = np.zeros((self.ydim-1,self.xdim-1))
x, y = self.m(lons, lats)
self.quad = ax.pcolormesh(x, y, self.z, cmap=plt.cm.Reds)
def init(self):
print 'update init'
self.quad.set_array([])
return self.quad
def __call__(self,i):
data = np.zeros((self.ydim-1,self.xdim-1))
for i in range(self.ydim-1):
for j in range(self.xdim-1):
data[i,j]=random.random()+4
self.quad.set_array(data.ravel())
return self.quad
fig = plt.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
m = Basemap(width=2000000,height=2000000,
resolution='l', projection='laea',\
lat_ts=10.,\
lat_0=64.,lon_0=10., ax=ax)
m.fillcontinents()
ud = UpdateQuad(ax, m, lons, lats)
anim = animation.FuncAnimation(fig, ud, init_func=ud.init,
frames=20, blit=False)
plt.show()
if __name__ == '__main__':
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.basemap import Basemap
import numpy as np
import random
lons = np.linspace(-5.,25., num = 25)[:50]
lats = np.linspace(56., 71., num = 25)[:50]
lons,lats = np.meshgrid(lons,lats)
plot_pcolor(lons,lats)
It looks like the set_data method should require an ndarray (not sure why the example I had followed was working correctly).
So in the init() function, you should use quad.set_array(np.array([])) rather than quad.set_array([]).
Other problems to be aware of:
As mentioned before, you also want set blit=False in your FuncAnimation() call.
I was also experiencing problems when I set the quad artist attribute animated to True. Leave that be (i.e. quad.set_animated(False), which is the default anyway).
If you do not specify the bounds via norm in your first pcolormesh() call, it will set them according to the data you pass (in my case null), which resulting in my getting blank animations. Setting them according to the data you will animate later in the initial call prevented this problem in my case.
pcolormesh() takes the bounding positions to the data field, which should be +1 in the y and x dimension of the data array. If the data array is equal (or greater than) the dimensions of the position data, pcolormesh() will omit any data outside of this boundary requirement. I thought that my data would just appear offset by one grid cell, but everything was all whacky before I passed the correct boundary positions. See another question of mine for calculating these HERE.
Older versions of matplotlib do not have very good error reporting. I recommend upgrading to the latest version if that is an option for you.
Some random trouble-shooting:
After updating matplotlib and basemap and attempting to implement this in my existing plotting routine, I received the following error:
ValueError: All values in the dash list must be positive
I first thought it had to do with my pcolormesh() objects, but it took me way too long to discover that it was due to my previous setting of the dash attribute in my m.drawmeridians() call to dashes=[1,0] for a solid meridian. In the new version of matplotlib the handling of dashes was changed to give this error. The new prefered method for setting a solid line for the dash attribute is dashes=(None,None), which I don't like.
Resulting animation:
Code example for above output:
def plot_pcolor(lons,lats):
class UpdateQuad(object):
def __init__(self,ax, map_object, lons, lats):
self.ax = ax
self.m = map_object
self.lons = lons
self.lats = lats
vmin = 0
vmax = 1
self.ydim, self.xdim = lons.shape
self.z = np.zeros((self.ydim-1,self.xdim-1))
levels = MaxNLocator(nbins=15).tick_values(vmin,vmax)
cmap = plt.cm.cool
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
x, y = self.m(lons, lats)
self.quad = self.ax.pcolormesh(x, y, self.z, alpha=0.9,
norm=norm, cmap=cmap,
vmin=vmin, vmax=vmax)
def init(self):
print 'update init'
self.quad.set_array(np.asarray([]))
return self.quad
def __call__(self,i):
for i in range(self.ydim-1):
for j in range(self.xdim-1):
self.z[i,j]=random.random()
self.quad.set_array(self.z.ravel())
return self.quad
fig, ax = plt.subplots()
m = Basemap(width=2000000,height=2000000,
resolution='l', projection='laea',\
lat_ts=10.,\
lat_0=64.,lon_0=10., ax=ax)
m.fillcontinents()
ud = UpdateQuad(ax, m, lons, lats)
anim = animation.FuncAnimation(fig, ud, init_func=ud.init,
frames=20, blit=False)
fig.tight_layout()
plt.show()
return ud.quad
if __name__ == '__main__':
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.basemap import Basemap
import numpy as np
import random
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
lons = np.linspace(-5.,25., num = 25)[:50]
lats = np.linspace(56., 71., num = 25)[:50]
lons,lats = np.meshgrid(lons,lats)
quad = plot_pcolor(lons,lats)

Categories