1

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.

enter image description here

1 Answer 1

2

Figured it out using the blit=True kwarg and defining an init() function to pass to 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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.