【问题标题】:How to use Matplotlib's animate function?如何使用 Matplotlib 的动画功能?
【发布时间】:2021-05-24 13:07:19
【问题描述】:

谁能看到我的代码到底有什么问题?我正在尝试生成我的结果的动画图,以查看它随时间的演变,结果只是我的数据的完整图,而不是更新动画。

sampleText.txt文件只是一个大小为(5000, 1)的numpy数组,数组的前5个条目是[[-0.01955058],[ 0.00658392[,[-0.00658371],[-0.0061325 ],[-0.0219136 ]]

import matplotlib.animation as animation
import time

fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot()

def animate(i):
    
    x = np.linspace(0, len(dataArray), len(dataArray))
    y = []

    for eachLine in x:
        y.append(eachLine * 10)
            
    ax1.clear()
    ax1.plot(x, y, color = 'red', alpha = 0.5)

ani = animation.FuncAnimation(fig, func = animate)

plt.show()

【问题讨论】:

  • 那么问题出在哪里?你有一半的问题和一半的minimal reproducible example 这里
  • @MadPhysicist 请查看我对问题的更新。我已经简化了示例并更清楚地显示了问题。我得到了整个数据的完整图,而不是我想要的更新动画
  • 感谢您的回复。你能提供一个数据样本吗?比如打电话给np.arangenp.random,而不仅仅是口头描述?
  • 我不是 100% 确定你的意思,但我的这是我的 '(5000,1)' numpy 数组的前 5 个条目看起来像 '[[-0.01955058] [ 0.00658392 ] [-0.00658371] [-0.0061325 ] [-0.0219136 ]]'
  • 您不需要确切的数组。只需提供一些生成类似内容的代码即可。请参阅minimal reproducible example 以供参考

标签: python matplotlib matplotlib-animation


【解决方案1】:

动画的基础是一种机制,其中动画函数为初始图形设置设置要更改的值。在本例中,线宽为 3,颜色为红色,x 和 y 为空列表。 xy 数据通过动画函数中的 i 链接到帧数。

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

fig = plt.figure() 

# marking the x-axis and y-axis 
axis = plt.axes(xlim =(0, 500), ylim =(0, 1000)) 

x = np.linspace(0, 500, 500) 
y = x*2
# initializing a line variable 
line, = axis.plot([], [], lw=2, color='r') 

def animate(i): 
    line.set_data(x[:i], y[:i]) 
    return line, 

anim = FuncAnimation(fig, animate, frames=500, blit=True, repeat=False) 
plt.show()

【讨论】:

  • 请参考official reference中的基础知识。如果我的回答对你有帮助,请考虑采纳为正确答案
  • 我会检查我的工作并让你知道。感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多