0

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?

1 Answer 1

2

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)

Single snap shot of 3 animate plots

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.