Home > Software design >  Python matplotlib loop not showing anything
Python matplotlib loop not showing anything

Time:01-20

I'm trying to make a graph that should update periodically using a while loop. This is the code:

import matplotlib.pyplot as plt
import numpy as np
import time

fig = plt.figure()

while True:
    data_to_plot = pd.DataFrame(predictions)
    data_to_plot.columns = ['A','B','C']
    data_to_plot.plot()
    plt.pause(10)
    fig.canvas.draw()
    fig.canvas.flush_events()

What it does is just showing a series of empty frames.

CodePudding user response:

Here's a modified version of your code that should work:

import matplotlib.pyplot as plt
import pandas as pd

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

while True:
    data_to_plot = pd.DataFrame(predictions)
    data_to_plot.columns = ['A','B','C']
    ax.clear()
    ax.plot(data_to_plot)
    plt.pause(10)
    fig.canvas.draw()

In this version, the while loop creates a new plot with the new data on each iteration, utilizing the clear() method to clear the previous plot before drawing a new one and the fig.canvas.draw() method to update the plot.

It is essential to import pandas as pd in order to make use of DataFrame. This ensures that the plot is always up-to-date and visually appealing.

  • Related