Plot not showing for animation matplotlib

坚强是说给别人听的谎言 提交于 2021-01-27 19:36:47

问题


I am trying to animate the numpy array C3, this is an array with one channel of electrode data and I want to plot it in real time using matplotlib.

I have created my update function but nothing is printing out, I though the the syntax is you pass i through to loop through the plots and the FuncAnimation should do the rest. Can someone please point me in the right direction?

Much appreciated!

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

data_skip = 50

def update_plot(i):
    plt.cla()
    
    plt.plot(C3[i:i+data_skip], t[i:i+data_skip])
    plt.scatter(C3[i], t[i], marker='o', color='r')
    
    plt.tight_layout()
    plt.show()
    
ani = FuncAnimation(plt.gcf(), update_plot, interval=1000)

plt.tight_layout()
plt.show()

回答1:


Remove plt.cla(), it will clear current axes. Every time you plot something on figure, plt.cla() then clears it.

You could confirm it by the following minimul example. It plots nothing

import matplotlib.pyplot as plt
import numpy as np

C3 = np.linspace(0.5, 10, 100)
t = np.linspace(0.5, 10, 100)

plt.plot(C3, t)

plt.cla()

plt.show()

Matplotlib documentation have an example to write animation code: simple_anim.py. You'd better explicitly declare fig and ax.

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

C3 = np.linspace(0.5, 10, 100)
t = np.linspace(0.5, 10, 100)

data_skip = 2

fig, ax = plt.subplots()


def update_plot(i):
    ax.plot(C3[i:i+data_skip], t[i:i+data_skip])
    ax.scatter(C3[i], t[i], marker='o', color='r')


ani = FuncAnimation(fig, update_plot, interval=1000)

plt.tight_layout()
plt.show()


来源:https://stackoverflow.com/questions/63534682/plot-not-showing-for-animation-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!