Live plotting from CSV file with matplotlib.animat

2020-06-27 09:49发布

问题:

I am attempting to plot data from a sensor that is continuously being written to a CSV file. While successful in creating a live plot, each new data entry creates an additional line that extends to the first data entry. See Below:

The Python 3.4 Script:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import datetime as dt
import csv



fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
x=[] ; y1=[]; y2=[]; y3=[]
def animate(i):
    with open( 'data_log.csv', 'r') as csvfile:
        
        alphasensefile = csv.reader(csvfile, delimiter = ',')
        next(alphasensefile, None)
        next(alphasensefile, None)
        next(alphasensefile, None)

        for column in alphasensefile:
            a = dt.datetime.strptime((column[0]), '%H:%M:%S')
            x.append((a))
            y1.append(column[1])
            y2.append(column[2])
            y3.append(column[3])




    
    ax1.clear()
    ax1.plot(x,y1)
ani = animation.FuncAnimation(fig, animate, interval=1000)

plt.show()

Running this script collects sensor data and records it to a CSV file. Every data entry recorded live from that start draws an additional line that goes to the first data entry point. Like so:

if I open the file while the sensor is not recording, only the last data entry is linked to the first point like so:

Data is recorded to the CSV file like so:

PM Data Recorded: 23 03 2018

Time, PM 1, PM 2.5, PM 10

16:12:10, 0.1173, 0.1802, 3.2022

Any thoughts to why this is occurring?

回答1:

FIX:

After a while playing around with the code, i changed the code to:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.dates as matdate
from matplotlib import style
import time
import datetime as dt
import csv

style.use('bmh')


fig = plt.figure()
ax = fig.add_subplot(1,1,1)


def animate(i):
    csvfile = open( 'data_log.csv', 'r+')       
    alphasensefile = csv.reader(csvfile, delimiter = ',')
    next(alphasensefile, None)
    next(alphasensefile, None)
    next(alphasensefile, None)

    x=[] ; y1=[]; y2=[]; y3=[]

    for column in alphasensefile:
        a = dt.datetime.strptime((column[0]), '%H:%M:%S')
        x.append((a))
        y1.append(column[1])
        y2.append(column[2])
        y3.append(column[3])

        ax.clear()
        ax.plot(x, y1, label = 'PM 1 ', linewidth=0.7)

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

plt.show()

This plots the data live and smooth without issues.