如何在 Python 中刷新情节

How to refresh plot in Python

我在制作图表时遇到了一些问题,我想知道是否有人可以帮助我。这是我的情况:

我有两个数组:一个用于温度值,另一个用于时间。

我的目标是制作一个表示温度随时间变化的图表,每次在我的数组中附加一个值时(每 0.2 秒)自动刷新一次。

这是我试过但根本不起作用的代码。我对 Python 一点也不放心,对所有这些错误感到抱歉

import matplotlib.pyplot as plt
import random
import time

# My arrays are empty at the beginning
raw_temp_bme = []
temps = []

plt.ion()

fig, ax = plt.subplots(figsize=(8, 6))
line1, = ax.plot(temps, raw_temp_bme, "r") 

plt.title("Température du BME680 en fonction du temps")
plt.xlabel("Temps en ms")
plt.ylabel("Température en °C")

start_time = time.time()

while True:
    # I append my two arrays
    raw_temp.append(round(random.uniform(15.0, 30.0), 2))
    temps.append(round(time.time() - start_time, 2))

    line1.set_xdata(temps)
    line1.set_ydata(raw_temp_bme)
    fig.canvas.draw()
    fig.canvas.flush_events()
    time.sleep(0.2)

这是我得到的截图

我的图表中没有任何内容。

非常感谢您

在我看来,主要问题不在于绘图,而在于添加到列表的方式。尝试将 get_temperature_bme680 替换为该函数的代码(或 post 该函数的代码,这样我们就不必猜测了)。此外,line1, = ax.plot(temps, raw_temp_bme, "r") 行可能不起作用,因为 raw_temp_bme 尚不存在。

这里是如何制作动画的最小示例:

使用更新的代码并打印两个列表的内容,很明显出了什么问题:需要设置 xlim/ylim 以使数据在绘图范围内。如果你插入

    ax.set_xlim(min(temps), max(temps))
    ax.set_ylim(min(raw_temp_bme), max(raw_temp_bme))

就在 fig.canvas.draw() 之前应该可以解决问题。

PS.: 您还必须更正 raw_temp.append(...).

中的变量名称

enter image description here raw_temp_bme get_temperature_bme680 是你必须正确重写程序的主要错误 Jupyter Notebook 中会详细显示错误,您必须查看给出的错误 在

可能您的数据只是绘制在未自动缩放的视图之外。最小示例:

import matplotlib.pyplot as plt
import random
import time

# My arrays are empty at the beginning
raw_temp_bme = [30]
temps = [0]

plt.ion()
fig, ax = plt.subplots(figsize=(8, 6))
line1, = ax.plot(temps, raw_temp_bme, "r") 

#simulating your sensor data
def get_temperature_bme680():
    x =  random.random()
    temps.append(temps[-1] + x)  
    raw_temp_bme.append(raw_temp_bme[-1] + 2 * random.random() - 1)
    if len(temps) > 50:
        temps[:] = temps[1:]
        raw_temp_bme[:] = raw_temp_bme[1:] 
    time.sleep(x)
     

while True:
    get_temperature_bme680() # my fonction to append my arrays
    line1.set_xdata(temps)
    line1.set_ydata(raw_temp_bme)
    ax.set_xlim(min(temps), max(temps))
    ax.set_ylim(min(raw_temp_bme), max(raw_temp_bme))
    fig.canvas.draw()
    fig.canvas.flush_events()
    time.sleep(0.0002)

plt.show()