2016-12-14 69 views
1

我有一段代码在matplotlib中绘制了我的cpu使用情况。不过,我觉得这段代码没有正确使用FuncAnimation函数。我目前在我的animate循环中使用clear()函数,我相信它会清除所有的轴和图形?我知道有许多方法可以清除曲线,而不是整个图形本身,但我不知道如何。当我运行代码时,它的输出很好,但是我的CPU使用率有明显的跳跃。所以编号1)有没有更好的方式来做我即将做的事情? (实时绘制我的CPU使用情况)。 2.)如果我的方式没问题,可以采取任何方法来减少资源密集度?更好的方式来实现matplotlib动画与从cpu的实时数据?

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() 

它看起来很好,当它运行,但我能听到我的笔记本电脑风扇加一点比我更喜欢的是什么做的。

enter image description here

回答

1

想通了使用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() 
相关问题