Shinigami Sin of Wrath
Shinigami Sin of Wrath

Reputation: 101

Animating Subplots

I'm trying to animate subplots. I have created subplots using matplotlib gridspec I want to animate them. I tried to find a solution online but couldn't understand how to proceed.

Please help.

Thanks in advance

Below is the code.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.animation as animation



def create_plot():
    n=500
    x1 = np.random.normal(loc=0.0,scale=1,size=n)
    x2 = np.random.gamma(2.5,2,size=n)
    x3 = np.random.exponential(3.5,n)+8
    x4 = np.random.uniform(-2.5,5,size=n)
    arts = []
    gspec = gridspec.GridSpec(2, 2)
    topleft_histogram = plt.subplot(gspec[0, 0])
    topright_histogram = plt.subplot(gspec[1:, 0])
    lowerleft_histogram  = plt.subplot(gspec[0,1:])
    lowerright_histogram = plt.subplot(gspec[1:, 1:])
    y1 = topleft_histogram.hist(x1, density=True, bins=100)
    y2 = topright_histogram.hist(x2, density=True, bins=100)
    y3 = lowerleft_histogram.hist(x3, density=True, bins=100)
    y4 = lowerright_histogram.hist(x4, density=True, bins=100)
    arts = [y1, y2, y3, y4]
    return arts ## return the artists created by `plt.plot()`
create_plot()

Subplots to be animated enter image description here

Upvotes: 1

Views: 410

Answers (1)

Girish Hegde
Girish Hegde

Reputation: 1515

Using FuncAnimation of matplotlib.animation you do something like this:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
     
# figsize as if required
fig = plt.figure(figsize=(7, 7))
topleft_histogram    = fig.add_subplot(221)
topright_histogram   = fig.add_subplot(222)
lowerleft_histogram  = fig.add_subplot(223)
lowerright_histogram = fig.add_subplot(224)


def create_plot(ith):
    print(ith)
    n=500

    topleft_histogram.clear()
    topright_histogram.clear()
    lowerleft_histogram.clear()
    lowerright_histogram.clear()

    x1 = np.random.normal(loc=0.0,scale=1,size=n)
    x2 = np.random.gamma(2.5,2,size=n)
    x3 = np.random.exponential(3.5,n)+8
    x4 = np.random.uniform(-2.5,5,size=n)

    y1 = topleft_histogram.hist(x1, density=True, bins=100)
    y2 = topright_histogram.hist(x2, density=True, bins=100)
    y3 = lowerleft_histogram.hist(x3, density=True, bins=100)
    y4 = lowerright_histogram.hist(x4, density=True, bins=100)
    return fig

n_frames = 2
anim = FuncAnimation(fig, create_plot, frames=np.arange(0, n_frames), interval=200)

anim.save('animation.gif', dpi=80, writer='imagemagick')

Resulting animation(only 2 frames generated):

enter image description here

Upvotes: 1

Related Questions