如何通过每个lin中的值来分隔和绘制数组中的线

2024-06-17 13:28:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

你们对我如何成功地将Ant1和Ant2的数据分离出来并用不同的颜色绘制在同一个图形上有什么意见吗?你知道吗


Tags: 数据importmatplotlibfigpltcolorsetanimation
1条回答
网友
1楼 · 发布于 2024-06-17 13:28:42

您可以简单地使用相同的轴绘制每个数据集。你知道吗

下面的方法使用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()

这将为您提供以下类型的输出:

demo plot

相关问题 更多 >