首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用subplot和FuncAnimation生成多行

使用subplot和FuncAnimation生成多行
EN

Stack Overflow用户
提问于 2020-09-25 00:51:38
回答 1查看 101关注 0票数 0

我正在尝试用FuncAnimation生成一个动画of this plot。这些线会随着时间的推移而变化,这就是我想用FuncAnimation捕捉到的。

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

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

代码语言:javascript
复制
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行)。有人知道是怎么做到的吗?我不需要使用我的代码模板,它可以是完全不同的东西。

EN

回答 1

Stack Overflow用户

发布于 2020-09-25 01:21:32

我已经改编了matplotlib animation示例:

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

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64050952

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档