实时温度绘图使用Python

2024-04-19 23:15:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做一个项目,它需要实时监控各种量,如温度、压力、湿度等。我正在采用一种方法,即使用matplotlib和drwnow绘制一个图形。在

HOST = "localhost"
PORT = 4223

UID1 = "tsJ" # S1

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_ptc import BrickletPTC
import numpy as np
import serial

import matplotlib
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter

import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')

from drawnow import *

# creating arrays to feed the data

tempC1 = []

def makeafig():

    # creating subplots
    fig1 = plt.figure(1)

    a = fig1.add_subplot(111)

    #setting up axis label, auto formating of axis and title
    a.set_xlabel('Time [s]', fontsize = 10)
    a.set_ylabel('Temperature [°C]', fontsize = 10)
    y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
    a.yaxis.set_major_formatter(y_formatter)
    title1 = "Current Room Temperature (Side1): " + str(temperature1/100) + " °C"
    a.set_title(title1, fontsize = 10)

    #plotting the graph
    a.plot(tempC1, "#00A3E0")

    #saving the figure
    fig1.savefig('RoomTemperature.png', dpi=100)

while True:

    ipcon = IPConnection() # Create IP connection
    ptc1 = BrickletPTC(UID1, ipcon) # S1 

    ipcon.connect(HOST, PORT) # Connect to brickd

    #setting the temperature from PTC bricklet

    temperature1 = ptc1.get_temperature()


    #processing data from a temperature sensor to 1st array
    dataArray1=str(temperature1/100).split(',')
    temp1 = float(dataArray1[0])
    tempC1.append(temp1)

    #making a live figure
    drawnow(makeafig)
    plt.draw()

这是我在互联网上发现的很好的方法,它正在起作用。我所面临的唯一问题是,如果我为其他传感器制作更多的阵列,那么它会耗费更多的时间,而且与秒表相比,所绘制的绘图会滞后于实时。在

对于任何一个有效率的实时图像获取方法都是有效的。 或者任何命令来清除已经打印的数组值?在

如果有人能帮我解决这个问题,我将不胜感激。在


Tags: theto方法fromimportmatplotlibformatterplt
1条回答
网友
1楼 · 发布于 2024-04-19 23:15:15

I'd like to ask that, does filling data in arrays continuosly makes the process slow or is it my misconception?

这个很容易测试;创建一个空列表并向其添加几千个值大约需要10^-4秒,所以这应该不是问题。对我来说有点奇怪,它实际上比创建和填充固定大小的numpy.ndarray(但这可能取决于列表/数组的大小)。在

我很快使用了您的makeafig()函数,将a = fig1.add_subplot(111)最多(包括)a.plot(..)放在一个简单的for i in range(1,5)循环中,a = fig1.add_subplot(2,2,i);这使{}慢了大约50%,但差异仅为0.1-0.2秒。这和你所经历的滞后是一致的吗?在

这就是我在没有实际数据的情况下可以测试的内容,我的下一步将是从ipcon=..到{}的时间。也许瓶颈仅仅是数据的检索?关于如何对Python脚本的一部分进行计时,我相信有几个例子,对于这类问题,下面的例子应该足够了:

import time
t0 = time.time()
# do something
dt = time.time() - t0

相关问题 更多 >