I have a piece of code that graphs my cpu usage in matplotlib. However I feel like this code is not utilizing the FuncAnimation function properly. I am currently using the clear() function in my animate loop which i believe clears everything even the axes and graph? I know there are ways of clearing just the graphed line and not the whole graph itself, but im not sure how. When I run the code it's output is fine but there is a noticeable jump in my cpu usage. So numebr 1.) Is there a better way in general of doing what im trying to do? (graph my cpu usage in real time). 2.) If my way is ok, any ways to make it less resource intensive?
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()
It looks fine when its running but I can hear my laptops fans increase a bit more than I like for what its doing.
