0

I am quite new to python 3 and I am currently learning a bit about animation.FuncAnimation in matplotlib. I wrote a small program which plots the cpu usage over time. However, as more and more data is plotted, the graph compresses to the left. I want the x axis values to keep shifting as the data is updated. I think this question was raised here : Updating the x-axis values using matplotlib animation . However, I was not able to follow it that well. I want to achieve something like this

:: http://www.roboticslab.ca/matplotlib-animation/

It would be great if someone can help me with this. Thanks !

Here is my code:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import psutil
%matplotlib widget
fig = plt.figure()
ax1 = fig.add_subplot(111)

cpu = []
def animate(i):
    cpu.append(psutil.cpu_percent())

    ax1.clear()
    ax1.plot(cpu)

ani = animation.FuncAnimation(fig, animate, interval = 1000)
plt.show()

Using Jupyter Lab 1.0.7

macOS 10.15

anirvan
  • 51
  • 4

1 Answers1

0

It looks like you've fallen into the same trap as 90% of people asking about animations and matplotlib, in that you are repeatedly calling plot() at each step of your iterations, instead of updating the properties of the existing one.

The general procedure for animations is to:

  • create your figure and all the fixed elements that do not need to be updated
  • create the artists that need to be updated, and keep a reference to them
  • in your loop, update (instead of replacing or creating new artists) the properties of the artists created in the previous step.

code:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import psutil

N = 50 # number of points to keep
cpu = np.full(shape=(N,), fill_value=np.nan)

fig, ax = plt.subplots()
line, = ax.plot(cpu, 'r-')
ax.set_ylim(0,100)
ax.set_xlim(0,N)

def animate(i):
    cpu[:-1] = cpu[1:] # shift values one place to the left
    cpu[-1] = psutil.cpu_percent()
    line.set_ydata(cpu)

ani = animation.FuncAnimation(fig, animate, interval = 1000)

enter image description here

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
  • thanks for the reply. love how this works. But is it possible to also plot the time elapsed (in seconds) in real-time ? – anirvan Apr 05 '20 at 06:43