,python,matplotlib,spyder"/>

首页 > 解决方案 > 当通过板读取串行数据时,在 SPYDER 中看不到实时更新图,它只显示错误“

问题描述

SPYDER 中的代码 我的输入数据格式为 33,45,56 34,46,23 类似多行串行数据从微控制器快速传入,我打算同时绘制数据,所以我创建了 2 个子图,2 行更新在一个,在其他子图中更新 1 行。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import serial

plt.style.use('fivethirtyeight')

sample = np.array([])
data1 = np.array([])
data2 = np.array([])
data3 = np.array([])
n = 0
s=serial.Serial('COM5', 9600)



def animate(i):
    global n,sample,data1,data2,data3

    a = s.readline()
    str= a.decode()
    
    #print(str)
    if (str.endswith("\n")):  # check if line ends with \n character
        list = str.split(',')  # split the line with delimiter comma

        print(list)  # prints the list of string type
        val1 = float(list[0])
        val2 = float(list[1])
        val3 = float(list[2])
        sample = np.append(sample, n)
        data1 = np.append(data1, val1)
        data2 = np.append(data2, val2)
        data3 = np.append(data3, val3)
        n+=1

        #plt.plot(x_vals,y_vals)
        plt.subplot(2,1,1)
        plt.cla()
        plt.plot(sample, data1, label='Channel 1')
        plt.plot(sample, data2, label='Channel 2')
        plt.xlim([0, 100])
        plt.ylim([0, 50])
        plt.legend()
        plt.subplot(2, 1, 2)
        plt.cla()
        plt.plot(sample, data3, '-m',label='Channel 3')
        plt.xlabel('sample')
        plt.ylabel('y value (unit)')
        plt.suptitle('Knee Joint Parameters')  # Super title creates the overall title for all subplots
        plt.xlim([0, 100])
        plt.ylim([0,100])
        plt.legend()
        plt.grid(True)
        plt.tight_layout()

    # write the data to target.txt


ani = FuncAnimation(plt.gcf(), animate, interval=1000) #this function is being called every 1 sec

plt.show()


s.close()

显示的错误是 <Figure size 432x288 with 0 Axes> 我正在尝试 spyder 中的代码

标签: pythonmatplotlibspyder

解决方案


推荐阅读