Annapoornima Koppad Annapoornima Koppad - 2 months ago 34
Python Question

Plot date and data continuously matplotlib

I have written the following piece of code that collects the data from a file, timestamps it and plots it. I have the working code below:

temp_data=0
x=[datetime.now() + timedelta(hours=-i) for i in range(5)]
y=[temp_data+i for i in range(len(x))]
while True:

f=open("/sys/class/thermal/thermal_zone0/temp", "r")

#timestamp the data
temp_time=datetime.now()

#read the data in the file to a variable and divide by 1000 to get correct value
temp_data=int(f.readlines()[0].strip())/1000
x=x[1:]
x.append(temp_time)
y=y[1:]
y.append(temp_data)
plt.gcf().autofmt_xdate()
plt.plot(x,y)
plt.show()
sleep(5)


print "Good Bye, Exiting the Program"
#close file after reading
f.close()


What happens right now is that, the plot gets displayed and I have to close the plot window for the next set of data to appear on the plot.

I want to extend this further, wherein my plot continuously plots the data after reading the file and timestamping it.

Thanks in advance.

Answer

You could open a figure and hold it.

temp_data=0
x=[datetime.now() + timedelta(hours=-i) for i in range(5)]
y=[temp_data+i for i in range(len(x))]
plt.figure() ###### Create figure
while True:

    f=open("/sys/class/thermal/thermal_zone0/temp", "r")

    #timestamp the data
    temp_time=datetime.now()

    #read the data in the file to a variable and divide by 1000 to get correct value
    temp_data=int(f.readlines()[0].strip())/1000
    x=x[1:]
    x.append(temp_time)
    y=y[1:]
    y.append(temp_data)
    plt.hold(True) ##### Hold it.
    plt.gcf().autofmt_xdate()
    plt.plot(x,y)
    plt.show()
    sleep(5)


print "Good Bye, Exiting the Program"
    #close file after reading
    f.close()
Comments