I am trying to figure out how to animate 3 subplots using matplotlib.animation
. My code is looking like this:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, sharex='col', sharey='row')
ax1.set_aspect('equal', 'datalim')
ax1.set_adjustable('box-forced')
ax2.set_aspect('equal', 'datalim')
ax2.set_adjustable('box-forced')
ax3.set_aspect('equal', 'datalim')
ax3.set_adjustable('box-forced')
#fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
def g(x, y):
return np.sin(x) + 0.5*np.cos(y)
def h(x, y):
return 0.5*np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
im1 = plt.imshow(f(x, y), cmap=plt.get_cmap('viridis'), animated=True)
plt.colorbar(im1)
im2 = plt.imshow(g(x, y), cmap=plt.get_cmap('viridis'), animated=True)
plt.colorbar(im2)
im3 = plt.imshow(h(x, y), cmap=plt.get_cmap('viridis'), animated=True)
plt.colorbar(im3)
def updatefig(*args):
global x, y
x += np.pi / 15.
y += np.pi / 20.
im1.set_array(f(x, y))
im2.set_array(g(x, y))
im3.set_array(h(x, y))
return im1,im2,im3
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
#plt.colorbar()
plt.show()
First thing - why don't I see the other two plots than im1? Second thing - how can I add the colorbars correctly to each one of the subplots?
This is happening because you are not referencing the other ax objects you created. Thus you keep referencing the same set axes. Same story with the color bars as well. You are pretty close you just need to point everything to the right object, have a look.
im1 = ax1.imshow(f(x, y), cmap=plt.get_cmap('viridis'), animated=True)
fig.colorbar(im1,ax=ax1)
im2 = ax2.imshow(g(x, y), cmap=plt.get_cmap('viridis'), animated=True)
fig.colorbar(im2,ax=ax2)
im3 = ax3.imshow(h(x, y), cmap=plt.get_cmap('viridis'), animated=True)
fig.colorbar(im3,ax=ax3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.