gpt4 book ai didi

python - 如何实时绘制中断线

转载 作者:行者123 更新时间:2023-12-01 08:49:04 24 4
gpt4 key购买 nike

我有湿度传感器,可以从环境中收集数据并将其存储在 data_temp.csv 中。问题是收集的一些数据是 None 值。当我绘制它时,图。显示了继续行,它忽略了 None 值。

我想要的是,绘制表中显示的值,当没有值时,停止该行,当该值再次出现时,绘制该行。

我的代码是:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.animation as animation
from datetime import datetime

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#4169E1') ##0079E7
def animate(i):
ftemp = 'data_temp.csv'
fh = open(ftemp)
hum = list()
timeC = list()
for line in fh:
pieces = line.split(',')
degree = pieces[0]
degree2 = pieces[1]
timeB= pieces[2]
timeA= timeB[:8]
time_string = datetime.strptime(timeA,'%H:%M:%S')
#print time_string
try:
hum1.append(float(degree))
timeC.append(time_string)
except:
print ("---------")
ax1 = fig.add_subplot(1,1,1,axisbg='white')

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%M'))
ax1.clear()
ax1.plot(timeC,hum1, 'c', linewidth = 2.3, label='Humidity',color="blue",marker='o',linestyle='dashed',markersize=10)
ax1.legend()
plt.title('Humidity')
plt.xlabel('Time')

ani = animation.FuncAnimation(fig, animate, interval = 6000)
plt.show()`

This is my data_temp.csv file

最佳答案

您可以使用numpy.ma - 屏蔽数组不显示某些数据。我将制作一个小演示,而不是整个动画,就说单个帧:

您的示例数据是:

None,24.0,12:18:49
40.0,24.0,12:18:55
41.0,24.0,12:18:59
40.0,24.0,12:19:02
None,24.0,12:19:06
None,24.0,12:19:09
None,24.0,12:19:13
None,24.0,12:19:19
41.0,24.0,12:19:22

代码:

import matplotlib.pyplot as plt
import numpy
from datetime import datetime
import numpy.ma

with open('data_temp.csv', 'r') as f:
times = []
hum = []

# parse the file
for line in f:
# split each line
spl = line.strip().split(',')
# append times - x axis points
times.append(datetime.strptime(spl[2][:8],'%H:%M:%S'))
# append humidities - y axis points is valie, else a placeholder -999
hum.append(float(spl[0]) if spl[0] != 'None' else -999)

fig = plt.figure()
ax = fig.add_subplot(111)

# convert to numpy arrays
hum = numpy.array(hum)
times = numpy.array(times)

# not let's mask all x-axis points where humidity is not valid, ie == -999
times_masked = numpy.ma.masked_where(hum == -999, times)
# let's also mask all y-axis points where humidity not valid
hum_masked = numpy.ma.masked_where(hum == -999, hum)

# plto as a step function
ax.step(times_masked, hum_masked)

它产生一个像这样的数字:

enter image description here

“无”条目被省略,但其余条目已就位。

关于python - 如何实时绘制中断线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53208276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com