实时图形错误

时间:2019-05-01 06:36:04

标签: python python-3.x matplotlib raspberry-pi sensor

我正在使用“实时”图,它将每10秒循环一次,从GPIO进行温度测量,并在适当的时间将该数据添加到matplotlib图中。我有相应的代码,但是当我尝试启动它时,x轴的max number of values根本不起作用,并且datetime值具有bugs-有时它显示黑色矩形,有时是数字当它显示数字时-类似于10:50, 11:00, 11:50, 12:00,但我想每10秒测量一次,而不是50分钟,10分钟等等……我不知道代码的哪一部分有问题,可以有人帮我吗? 这是代码



import datetime
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import RPi.GPIO as GPIO
import dht11
from datetime import datetime as dd
import time as tt
import matplotlib.dates as md
import dateutil

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 4
instance = dht11.DHT11(pin=4)



# This function is called periodically from FuncAnimation
def animate(i, xs, ys):

    # Read temperature (Celsius) from TMP102
    result = instance.read()
    temp_c = result.temperature
    # Add x and y to lists
    tem = tt.strftime("%H:%M", tt.localtime(tt.time()))
    dates = [dateutil.parser.parse(tem)]
    ax=plt.gca()
    ax.set_xticks(dates)
    xfmt = md.DateFormatter('%H:%M')
    ax.xaxis.set_major_formatter(xfmt)
    if result.is_valid():
        xs.append(dates)
        ys.append(temp_c)

    # Limit x and y lists to 5 items
        xs = xs[-5:]
        ys = ys[-5:]

    # Draw x and y lists
        ax.clear()
        ax.plot(xs, ys)

    # Format plot
        plt.xticks(rotation=45, ha='right')
        plt.subplots_adjust(bottom=0.30)
        plt.title('Temperature over Time')
        plt.ylabel('Temperature (deg C)')

# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000)
plt.show()        

0 个答案:

没有答案