Clear old Matplotlib data?

Question:

I am attempting to plot live CPU data from my computer and update the corresponding graph to display the data. The chart scrolls as intended, but there’s one major problem. As time goes on, the data (likely stored within Matplotlib) doesn’t get deleted.

I can successfully keep the actual python list at 50 items by using data = data[-50:], but my program still slows down over time. Somehow, I am still able to scroll back in time as the program is running to view data from over 50 iterations ago, which I assume is what slows the script down. Is it stored elsewhere? How do I prevent this?

I chose not to use FuncAnimation from Matplotlib since I have other operations that happen inside the while loop beside the animation. If there is a way to use FuncAnimation while simultaneously doing other things in the while loop, please let me know.

My ultimate goal is to use this logic to plot live stock data, but I created this simplified example to make this an easier problem to fix. I am using python version 3.9.7 and Matplotlib 3.6.2.

Thanks in advance! The code is below.

import time
import psutil
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot()
fig.show()

x, data = [], []
i = 1

while True:
    x.append(i)
    data.append(psutil.cpu_percent())
    x = x[-50:]
    data = data[-50:]

    ax.plot(x, data, color='black')
    fig.canvas.flush_events()
    ax.set_xlim(left=max(0, i - 50), right=i + 10)
    fig.canvas.draw()

    print(len(data))
    i += 1
    time.sleep(.1)
Asked By: Ryan Hermes

||

Answers:

You can use the ax.clear() method before calling ax.plot(x, data, color='black') in each iteration of the loop.

Answered By: Aarush Killer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.