使用matplotlib.animation从CSV文件实时打印-绘制到第一个条目的数据错误
我正试图从一个持续写入CSV文件的传感器中绘制数据。在成功创建实时绘图时,每个新数据项都会创建一条延伸到第一个数据项的附加线。见下文: Python 3.4脚本:使用matplotlib.animation从CSV文件实时打印-绘制到第一个条目的数据错误,csv,animation,matplotlib,plot,graph,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)
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文件中。从该开始实时记录的每个数据输入都会绘制一条额外的线,该线通向第一个数据输入点。像这样:
如果在传感器未记录时打开文件,则只有最后一个数据条目链接到第一个点,如下所示:
数据被记录到CSV文件中,如下所示:
记录的PM数据:23 03 2018
时间,下午一时,下午二时五分,晚上十时
16:12:10,0.1173,0.1802,3.2022
有没有想过为什么会发生这种情况?修复:
玩了一会儿代码后,我将代码更改为:
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()
这将实时、平滑地绘制数据,不会出现任何问题