我是Python的新手,我正在尝试从不断增长的CSV中提取数据,并创建实时更新图。我想创建两个不同的x,y数组,具体取决于数据通过哪个天线(用逗号分隔的每行数据中的一个值)。数据文件如下所示:
TimeStamp, ReadCount, Antenna, Protocol, RSSI, EPC, Sensor
09/21/2016 15:24:40.560, 5499, 1, GEN2, -21, E036112D912508B3, 23.78,47.00,0.00,2.21, (Infinity%)
09/21/2016 15:24:41.138, 5506, 1, GEN2, -9, E036112D912508B3, 23.99,46.00,0.00,2.26, (Infinity%)
09/21/2016 15:24:41.623, 5513, 1, GEN2, -25, E036112D912508B3, 23.99,46.00,0.00,2.26, (Infinity%)
09/21/2016 15:24:42.120, 5520, 1, GEN2, -18, E036112D912508B3, 23.78,46.00,0.00,2.26, (Infinity%)
09/21/2016 15:24:42.633, 5527, 1, GEN2, -12, E036112D912508B3, 23.99,45.00,0.00,2.23, (Infinity%)
09/21/2016 15:24:43.211, 5534, 1, GEN2, -9, E036112D912508B3, 23.99,46.00,0.00,2.26, (Infinity%)
09/21/2016 15:24:43.744, 5541, 1, GEN2, -16, E036112D912508B3, 23.99,46.00,0.00,2.26, (Infinity%)

我已成功显示图表的代码,但只是将所有数据行接收到一个x,y数组中,如下所示:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime
offset = -7.4954
slope = 0.9548
fig = plt.figure(facecolor='#07000d')
ax1 = fig.add_subplot(111, axisbg='#07000d')
ax1.spines['bottom'].set_color("#5998ff")
ax1.spines['top'].set_color("#5998ff")
ax1.spines['left'].set_color("#5998ff")
ax1.spines['right'].set_color("#5998ff")
def animate(i):
graph_data = open('SensorLog.csv','r').read()
dataArray = graph_data.split('\n')
xar=[]
yar=[]
for eachLine in dataArray:
if 'TimeStamp' not in eachLine:
if len(eachLine)>1:
t,rc,ant,prot,rssi,epc,temp,ten,powr,unpowr,inf=(eachLine.split(','))
time = datetime.strptime(t, '%m/%d/%Y %H:%M:%S.%f')
clock = time.strftime('%I:%M')
xs = matplotlib.dates.datestr2num(clock)
hfmt = matplotlib.dates.DateFormatter('%m/%d/%Y\n%I:%M:%S %p')
# Convert tension
tension = int(float(ten)*float(slope)+float(offset))
xar.append(xs)
yar.append(tension)
ax1.clear()
ax1.grid(True, color='w')
plt.ylabel('Tension (lb)',color='w', fontsize=20)
plt.title('Spiral 1 Tension',color='w', fontsize=26)
ax1.tick_params(axis='y', colors='w')
ax1.tick_params(axis='x', colors='w')
ax1.xaxis.set_major_formatter(hfmt)
fig.autofmt_xdate()
ax1.plot (xar,yar, 'c', linewidth=2)
ani = animation.FuncAnimation(fig, animate, interval=10000)
plt.show()

我正在尝试将天线1和2上的数据分开,并使用不同的彩色线图在同一图表(共享x轴)上绘制每个数据...我的尝试在这里,但它不起作用:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime
offset = -7.4954
slope = 0.9548
fig = plt.figure(facecolor='#07000d')
ax1 = fig.add_subplot(111, axisbg='#07000d')
ax2 = fig.add_subplot(111, axisbg='#07000d')
ax1.spines['bottom'].set_color("#5998ff")
ax1.spines['top'].set_color("#5998ff")
ax1.spines['left'].set_color("#5998ff")
ax1.spines['right'].set_color("#5998ff")
ax2.spines['bottom'].set_color("#5998ff")
ax2.spines['top'].set_color("#5998ff")
ax2.spines['left'].set_color("#5998ff")
ax2.spines['right'].set_color("#5998ff")
def animate(i):
graph_data = open('SensorLog.csv','r').read()
dataArray = graph_data.split('\n')
xar=[]
yar=[]
xar2=[]
yar2=[]
for eachLine in dataArray:
if 'TimeStamp' not in eachLine:
if len(eachLine)>1:
t,rc,ant,prot,rssi,epc,temp,ten,powr,unpowr,inf=(eachLine.split(','))
time = datetime.strptime(t, '%m/%d/%Y %H:%M:%S.%f')
clock = time.strftime('%I:%M')
xs = matplotlib.dates.datestr2num(clock)
hfmt = matplotlib.dates.DateFormatter('%m/%d/%Y\n%I:%M:%S %p')
# Convert tension
tension = int(float(ten)*float(slope)+float(offset))
if ant == '1':
xar.append(xs)
yar.append(tension)
if ant == '2':
xar2.append(xs)
yar2.append(tension)
ax1.clear()
ax2.clear()
ax1.grid(True, color='w')
ax2.grid(True, color='w')
plt.ylabel('Tension (lb)',color='w', fontsize=20)
plt.title('Spiral 1 Tension',color='w', fontsize=26)
ax1.tick_params(axis='y', colors='w')
ax1.tick_params(axis='x', colors='w')
ax1.xaxis.set_major_formatter(hfmt)
ax2.tick_params(axis='y', colors='w')
ax2.tick_params(axis='x', colors='w')
ax2.xaxis.set_major_formatter(hfmt)
fig.autofmt_xdate()
ax1.plot (xar,yar, 'c', linewidth=2)
ax2.plot (xar2,yar2,'r', linewidth=3)
ani = animation.FuncAnimation(fig, animate, interval=10000)
plt.show()

你们有没有关于如何成功分离ant 1和ant 2数据以及在不同颜色的同一图上绘制它的信息?
答案 0 :(得分:0)
您可以使用相同的轴简单地绘制每个数据集。
以下方法使用Python csv.DictReader
来帮助读取数据,并使用defaultdict(list)
自动将数据拆分为基于每行天线的列表。
这也添加了代码来解决您的评论,这些评论将数据点分组的时间间隔不超过60秒,并且只显示最后5分钟的条目:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime, timedelta
import collections
import csv
offset = -7.4954
slope = 0.9548
def plot(ax, data, colour, width):
if data:
last_dt = data[0][0]
sixty = timedelta(seconds=60)
x = []
y = []
# Plot groups of data not more than 60 seconds apart
for dt, ten in data:
if dt <= last_dt + sixty:
x.append(dt)
y.append(ten)
else:
ax.plot(matplotlib.dates.date2num(x), y, colour, linewidth=width)
x = [dt]
y = [ten]
last_dt = dt
ax.plot(matplotlib.dates.date2num(x), y, colour, linewidth=width)
def animate(i, fig, ax):
# Read in the CSV file
data = collections.defaultdict(list)
fields = ["TimeStamp", "ReadCount", "Antenna", "Protocol", "RSSI", "EPC", "Temp", "Ten", "Powr", "Unpowr", "Inf"]
with open('SensorLog.csv') as f_input:
csv_input = csv.DictReader(f_input, skipinitialspace=True, fieldnames=fields)
header = next(csv_input)
# Separate the rows based on the Antenna field
for row in csv_input:
try:
data[row['Antenna']].append(
[datetime.strptime(row['TimeStamp'], '%m/%d/%Y %H:%M:%S.%f'),
int(float(row['Ten']) * float(slope) + float(offset))])
except TypeError as e:
pass
# Drop any data points more than 5 mins older than the last entry
latest_dt = data[row['Antenna']][-1][0] # Last entry
not_before = latest_dt - timedelta(minutes=5)
for antenna, entries in data.items():
data[antenna] = [[dt, count] for dt, count in entries if dt >= not_before]
# Redraw existing axis
ax.clear()
ax.spines['bottom'].set_color("#5998ff")
ax.spines['top'].set_color("#5998ff")
ax.spines['left'].set_color("#5998ff")
ax.spines['right'].set_color("#5998ff")
hfmt = matplotlib.dates.DateFormatter('%m/%d/%Y\n%I:%M:%S %p')
ax.xaxis.set_major_formatter(hfmt)
fig.autofmt_xdate()
plot(ax, data['1'], 'c', 2) # Antenna 1
plot(ax, data['2'], 'r', 3) # Antenna 2
ax.grid(True, color='w')
plt.ylabel('Tension (lb)', color='w', fontsize=20)
plt.title('Spiral 1 Tension', color='w', fontsize=26)
ax.tick_params(axis='y', colors='w')
ax.tick_params(axis='x', colors='w')
fig = plt.figure(facecolor='#07000d')
ax = fig.add_subplot(111, axisbg='#07000d')
ani = animation.FuncAnimation(fig, animate, fargs=(fig, ax), interval=1000)
plt.show()
这会给你以下类型的输出: