首页 > 解决方案 > 使用 subplot 和 FuncAnimation 生成多行

问题描述

我正在尝试使用 FuncAnimation生成此情节的动画。这些线条会随着时间而变化,这就是我想用 FuncAnimation 捕捉的内容。

目前,我可以生成动画,但每个子图只有一行。

我的动画代码大致如下所示:

y1 = np.random.rand(1000, 5, 80)
y2 = np.random.rand(1000, 5, 80)
fig, axes = plt.subplots(1 ,2)
lines = []
x = np.linspace(0, 1, 1000)

for index, ax in enumerate(axes.flatten()):
   if index == 0:
      l, = ax.plot(y1[:,0,0], x)
   if index == 1:
      l, = ax.plot(y2[:,0,0], x)
   lines.append(l)

def run(it):
    for index, line in enumerate(lines):
        if index == 0:
           line.set_data(x, y1[:, 0, it]
        if index == 1:
           line.set_data(x, y2[:, 0, it]
    return lines

ani = animation.FuncAnimation(fig, run, frames =80)
plt.show()

但是,同样,该代码仅生成每个子图的行。我想每个子图有多行(在示例代码中,这将是 5 行)。有谁知道怎么做?我不必使用我的代码模板,它可能是完全不同的东西。

标签: pythonmatplotlibanimation

解决方案


我改编了matplotlib 动画示例:

您可以在评论中看到我添加/更改了哪些行。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, (ax, ax2) = plt.subplots(2) #create two axes
xdata, ydata = [], []
ln, = ax.plot([], [], 'ro')
ln2, = ax2.plot([], [], 'go') # added

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    ax2.set_xlim(0, 2*np.pi) # added
    ax2.set_ylim(-1, 1) # added
    return ln,ln2 # added ln2

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    ln2.set_data(xdata, ydata) # added
    return ln, ln2 #added ln2

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

推荐阅读