0

我是 python 新手,正在执行一些小项目,同时观看教程以使我能够学习。

我最近一直在使用一些 API 来收集数据——我将这些数据保存在 CSV 文件中,然后打开 CSV 文件以将数据显示为图表。

我希望图表显示数据LIVE,但这样做我只希望一次在屏幕上显示 10 个值,因此当绘制第 11 个值时,第一个不再可见,除非使用滚动功能回头查看它..

我已经设法将绘制 CSV 文件中的实时数据的代码以及一些以所需格式创建图形的代码汇总在一起 - 但由于我对 python 很陌生,我不确定如何制作它们一起工作..任何建议将不胜感激。

下面是我创建的用于从 CSV 文件读取和绘图的代码:

import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

index = count()

def animate(i):
    data = pd.read_csv('x.csv')
    x = data['Time']
    y = data['R1Temp']
    y1 = data['R2Temp']
    y2 = data['R3Temp']

    plt.cla()

    plt.plot(x, y, marker = 'o', label='Room 1 Temp')
    plt.plot(x, y1, marker = 'o', label='Room 2 Temp')
    plt.plot(x, y2, marker = 'o', label='Room 3 Temp')   

    plt.xlabel("Time")
    
    plt.ylabel("Temperature °C")
    plt.title("Live temperature of Rooms")
    
    plt.legend(loc='upper left')
    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()

下面是显示我希望图表格式化数据图的方式的代码:

import numpy as np
import matplotlib.pyplot as plt

import matplotlib.animation as animation


def update(frame):
    global x, y

    start = x[max(frame-PAN//2, 0)] 
    start = x[max(frame-PAN+1, 0)] 
    end = start + PAN

    ax.set_xlim(start, end)

    start, end = ax.get_xlim()
    ax.xaxis.set_ticks(np.arange(start, end, TICK))

    ax.figure.canvas.draw()

    line1.set_data(x[0:frame+1], y[0:frame+1])

    return (line1,)

# main
NUM = 100
TICK = 1
PAN = 10

x = np.arange(start=1, stop=NUM + 1, step=1)

for i in range(NUM):
    y = np.random.rand(NUM) * 100

fig, ax = plt.subplots()

ax.set_xlim(0, PAN)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, TICK))

ax.set_ylim(0, 100)

line1, = ax.plot([], [], color="r")

ani = animation.FuncAnimation(fig, update, frames=len(x), interval=1000, repeat=False)

plt.show()

我尝试了很多方法将它们合并在一起,但我似乎无法找到正确的方法来解决它。

提前致谢!!

4

1 回答 1

0

显示最后 N 个时间点非常容易。只需用于DataFrame.tail()获取数据框的最后 N 行。

请注意,在制作动画时,推荐的方法是在动画代码之外创建您的轴和艺术家,并且只在动画代码内更新您的艺术家的数据

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


fig, ax = plt.subplots()

l1, = ax.plot([], [], marker='o', label='Room 1 Temp')
l2, = ax.plot([], [], marker='o', label='Room 2 Temp')
l3, = ax.plot([], [], marker='o', label='Room 3 Temp')

plt.xlabel("Time")
plt.ylabel("Temperature °C")
plt.title("Live temperature of Rooms")
plt.legend(loc='upper left')
plt.tight_layout()


def animate(i, N):
    data = pd.read_csv('x.csv').tail(N)

    l1.set_data(data['Time'], data['R1Temp'])
    l2.set_data(data['Time'], data['R2Temp'])
    l3.set_data(data['Time'], data['R3Temp'])

    ax.relim()
    ax.autoscale_view()

    return l1, l2, l3


ani = FuncAnimation(fig, animate, interval=1000, frames=None, fargs=(10,))

plt.show()
于 2020-12-30T14:25:02.487 回答