使用matplotlib.animation从CSV文件中实时绘图 - 将数据绘制到第一个输入错误

时间:2018-03-23 05:32:44

标签: csv animation matplotlib plot graph

我正在尝试从连续写入CSV文件的传感器绘制数据。在成功创建实时绘图的同时,每个新数据条目都会创建一个扩展到第一个数据条目的附加行。见下文:

Python 3.4脚本:

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()

运行此脚本会收集传感器数据并将其记录到CSV文件中。从该开始实时记录的每个数据条目都会绘制一条到第一个数据输入点的附加行。像这样:

Figure 1

如果我在传感器未录制时打开文件,则只有最后一个数据条目链接到第一个点,如下所示:

Figure 2

数据被记录到CSV文件中,如下所示:

  

PM数据记录:23 03 2018

     

时间,PM 1,PM 2.5,PM 10

     

16:12:10,0.1173,0.1802,3.2022

有关为何发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:0)

FIX:

经过一段时间玩代码后,我将代码更改为:

  final myJsonCodec = new JsonCodec.withReviver((dynamic key, dynamic value) {
     if (value is int) return value.toDouble();
     return value;
  });

这样可以毫无问题地实时绘制数据。