我是 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()
我尝试了很多方法将它们合并在一起,但我似乎无法找到正确的方法来解决它。
提前致谢!!