Python 使用来自cpu的实时数据实现matplotlib动画的更好方法?

Python 使用来自cpu的实时数据实现matplotlib动画的更好方法?,python,matplotlib,Python,Matplotlib,我有一段代码可以在matplotlib中显示我的cpu使用情况。但是我觉得这段代码没有正确地使用FuncAnimation函数。我目前正在使用动画循环中的clear()函数,我相信该函数可以清除所有内容,包括轴和图形?我知道有几种方法可以清除图形线,而不是整个图形本身,但我不知道如何清除。当我运行代码时,它的输出是好的,但是我的cpu使用率有一个明显的跳跃。所以numebr 1)总的来说,有没有更好的方法来做我想做的事情?(实时绘制我的cpu使用情况)。2)如果我的方法可行,有什么方法可以降低资

我有一段代码可以在matplotlib中显示我的cpu使用情况。但是我觉得这段代码没有正确地使用
FuncAnimation
函数。我目前正在使用动画循环中的
clear()
函数,我相信该函数可以清除所有内容,包括轴和图形?我知道有几种方法可以清除图形线,而不是整个图形本身,但我不知道如何清除。当我运行代码时,它的输出是好的,但是我的cpu使用率有一个明显的跳跃。所以numebr 1)总的来说,有没有更好的方法来做我想做的事情?(实时绘制我的cpu使用情况)。2)如果我的方法可行,有什么方法可以降低资源密集度

import psutil
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
from collections import deque

fig = plt.figure()
ax1 = fig.add_subplot(111)

y_list = deque([-1]*150)


def animate(i):

    y_list.pop()
    y_list.appendleft(psutil.cpu_percent(None,False))

    ax1.clear()
    ax1.plot(y_list)
    ax1.set_xlim([0, 150])
    ax1.set_ylim([0, 100])

ax1.axes.get_xaxis().set_visible(False)

anim = animation.FuncAnimation(fig, animate, interval=200)
plt.show()
当它运行的时候看起来不错,但我能听到我的笔记本电脑的粉丝们增加了一点,比我喜欢的多


使用
blit=True
kwarg并定义一个
init()
函数传递给
FuncAnimation

fig = plt.figure()
ax = plt.axes(xlim=(0, 200), ylim=(0, 100))
line, = ax.plot([],[])

y_list = deque([-1]*400)
x_list = deque(np.linspace(200,0,num=400))


def init():
    line.set_data([],[])
    return line,


def animate(i):
    y_list.pop()
    y_list.appendleft(psutil.cpu_percent(None,False))
    line.set_data(x_list,y_list)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=100, blit=True)

plt.show()