Animating Subplots

Sep 14 2020

Tôi đang cố tạo hoạt ảnh cho các tình tiết phụ. Tôi đã tạo các tình huống phụ bằng cách sử dụng matplotlib gridspecTôi muốn làm sinh động chúng. Tôi đã cố gắng tìm giải pháp trực tuyến nhưng không thể hiểu cách tiếp tục.

Hãy giúp tôi.

Cảm ơn trước

Dưới đây là mã.

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

Các tình tiết phụ được làm hoạt hình

Trả lời

1 GirishDattatrayHegde Sep 14 2020 at 21:11

Sử dụng FuncAnimation của matplotlib.animationbạn làm như sau:

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

Hoạt ảnh kết quả (chỉ tạo 2 khung hình):