Animação de subtramas

Sep 14 2020

Estou tentando animar subtramas. Eu criei subtramas usando matplotlib gridspecQuero animá-los. Tentei encontrar uma solução online, mas não consegui entender como proceder.

Por favor ajude.

desde já, obrigado

Abaixo está o código.

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()

Subtramas a serem animadas

Respostas

1 GirishDattatrayHegde Sep 14 2020 at 21:11

Usando FuncAnimation de matplotlib.animationvocê fazer algo como isto:

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')

Animação resultante (apenas 2 frames gerados):