如何实时绘制停产线

时间:2018-11-08 13:00:20

标签: python matplotlib

我有湿度传感器,该传感器从环境中收集数据并将其存储在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

1 个答案:

答案 0 :(得分:1)

您可以使用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

'None'条目被省略,但其余条目就位。