【问题标题】:Python- Real time sensor data graphingPython-实时传感器数据绘图
【发布时间】:2021-01-13 11:09:13
【问题描述】:

我正在从 MPU6050 加速度计获取传感器数据。传感器给我 x、y 和 z 轴的加速度。我目前只是想绘制 x 加速度与时间的关系图。理想情况下,我会将它们全部绘制在一起,但我无法使单个 x 数据与时间图起作用,所以我现在只关注这一点。我的代码如下:

from mpu6050 import mpu6050
import time
import os
from time import sleep
from datetime import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
mpu = mpu6050(0x68)

#create csv file to save the data
file = open("/home/pi/Accelerometer_data.csv", "a")
i=0
if os.stat("/home/pi/Accelerometer_data.csv").st_size == 0:
        file.write("Time,X,Y,Z\n")

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


def animate(i, xs, ys):

    # Read acceleration from MPU6050
    accel_data = mpu.get_accel_data()
    
    #append data on the csv file
    i=i+1
    now = dt.now()
    file.write(str(now)+","+str(accel_data['x'])+","+str(accel_data['y'])+","+str(accel_data['z'])+"\n")
    file.flush()

    # Add x and y to lists
    xs.append(dt.now().strftime('%H:%M:%S.%f'))
    ys.append(str(accel_data['x']))
    
    # Limit x and y lists to 20 items
    xs = xs[-10:]
    ys = ys[-10:]

    # 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('MPU6050 X Acceleration over Time')
    plt.ylabel('X-Acceleration')

#show real-time graph
ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys), interval=1000)
plt.show()

csv 文件保存准确的数据。该图确实随着时间而更新,但它给了我一条直线。这是因为 y 轴是如何更新的。见下图:

如您所见,y 轴不是按升序排列的。有人可以帮我解决吗?另外,如何将图形 y 轴上的数字四舍五入为 5 个有效数字?我尝试使用 round() 函数,但它不允许。

谢谢!

【问题讨论】:

    标签: python matplotlib graph real-time sensors


    【解决方案1】:

    要使 y 轴按升序排列,我认为您必须使 ys 浮点值而不是字符串值:ys.append(float(accel_data['x'])) 要将 y 轴上的数字四舍五入到 5 个有效数字,您可以查看此问题的答案:Matplotlib: Specify format of floats for tick labels

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      • 2016-03-12
      • 2021-01-26
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多