Skip to main content
 首页 » 编程设计

python之连续绘制日期和数据 matplotlib

2025年04月02日8itcoder

我编写了以下代码,用于从文件中收集数据、为其添加时间戳并绘制它。我有以下工作代码:

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() 

现在发生的事情是,绘图得到显示,我必须关闭绘图窗口,以便下一组数据出现在绘图上。

我想进一步扩展它,其中我的绘图在读取文件并为其添加时间戳后连续绘制数据。

提前致谢。

请您参考如下方法:

您可以打开一个图形并按住它。

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()