Reputation: 839
I have 16 contour plots with changing titles and I want to just create an animation from the 16 contour plots.
I first set up the images and the data below, but I am having little luck in the animation part. I am trying to follow this example but I'm struggling: Increase the speed of redrawing contour plot in matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
import time
import pandas as pd
title = pd.date_range('1968-1-1','1969-04-01',
freq='MS').strftime("%b %Y").tolist()
data = np.random.rand(16,30,40)
fig, axes = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
for i,t,ax in zip(range(16),title, axes.ravel()):
x = ax.contourf(data[i],levels = np.arange(-.6,.6,.03), extend='both')
ax.set_title(t)
ax.grid()
cbaxes = fig.add_axes([1.02,.5,.05,.2]) # [left, bottom, width, height],
cbar = fig.colorbar(x, cax = cbaxes, fraction=.02)
cbar.set_label('cb', labelpad=15, y=.5, rotation=90)
plt.tight_layout()
plt.show()
My attempt at the animation part:
levels = np.arange(-.6,.6,.03)
fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
p = [ax.contour(data[0],levels=levels)]
def update(i):
for tp in range(16):
tp.remove()
p[0] = ax.contour(data[i], levels)
t[1:] = t[0:-1]
t[0] = time.time()
timelabel.set_text("{:.3f} fps".format(-1./np.diff(t).mean()))
return p[0]
ani = matplotlib.animation.FuncAnimation(fig, update, frames=16,
interval=30, blit=True, repeat=True) ## increasing interval slows it down!
ani.save("test.mp4")
plt.show()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-57-d70067088c5b> in <module>
3 fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
4
----> 5 p = [ax.contour(data[0],levels=levels)]
6
7 def update(i):
AttributeError: 'numpy.ndarray' object has no attribute 'contour'
The error doesn't recognize contour or contourf... How do I make a movie/animation of the 16 contour plots?
Upvotes: 0
Views: 407
Reputation: 138
This will give you an array with all subplots:
fig, ax = plt.subplots(nrows=4, ncols=4, figsize=(15,10)) #15, 25
You have to index the ax
array to plot on the subfigures:
# plot on the upper left subfigure
ax[0,0].contour(data[0],levels=levels)
Upvotes: 1