【问题标题】:Matplotlib Live Graph - Using Time as x-axis valuesMatplotlib Live Graph - 使用时间作为 x 轴值
【发布时间】:2018-04-27 09:25:25
【问题描述】:

我只是想知道是否可以将时间用作 matplotlib 实时图的 x 轴值。 如果是这样,应该怎么做?我一直在尝试许多不同的方法,但最终都会出错。 这是我当前的代码:

update_label(label):

    def getvoltage():

        f=open("VoltageReadings.txt", "a+")
        readings = [0]*100
        maxsample = 100
        counter = 0

        while (counter < maxsample):

            reading = adc.read_adc(0, gain=GAIN)
            readings.append(reading)
            counter += 1

        avg = sum(readings)/100
        voltage = (avg * 0.1259)/100
        time = str(datetime.datetime.now().time())
        f.write("%.2f," % (voltage) + time + "\r\n")
        readings.clear()

        label.config(text=str('Voltage: {0:.2f}'.format(voltage)))
        label.after(1000, getvoltage)
    getvoltage()

def animate(i):
    pullData = open("VoltageReadings.txt","r").read()
    dataList = pullData.split('\n')
    xList=[]
    yList=[]
    for eachLine in dataList:
        if len(eachLine) > 1:
            y, x = eachLine.split(',')
            xList.append(float(x)))
            yList.append(float(y))
            a.clear()
    a.plot(xList,yList)

这是我尝试过的最新方法之一,但出现错误提示

ValueError: could not convert string to float: '17:21:55'

我已经尝试找到将字符串转换为浮点数的方法,但我似乎做不到

非常感谢您的帮助和指导,谢谢:)

【问题讨论】:

  • 如果你的意思是“实时图形”是一个类似示波器的显示,恕我直言 matplotlib 不是完美的工具,因为它是为可发布的美丽图而设计的。看看 PyQtGraph (pyqtgraph.org) - 它的开发正是考虑到这种应用程序
  • 实时图表应该显示电池电压读数以及时间,以分析一段时间内的电池健康状况
  • 隐式类型转换 float(x) 仅适用于字符串,它只包含一个作为数字可解释的字符串。只要里面有其他东西(例如':'),它就会失败。你已经导入了datetime,所以试试例如datetime.datetime.strptime(x, '%H:%M:%S')

标签: python python-3.x matplotlib tkinter


【解决方案1】:

我认为您应该使用 datetime 库。您可以使用此命令 date=datetime.strptime('17:21:55','%H:%M:%S') 读取日期,但您必须通过设置 date0=datetime(1970, 1, 1) 来使用儒略日期作为参考 您还可以将时间序列的起点用作 date0,然后将日期设置为 @987654323 @。使用循环计算文件中每一行的实际日期和参考日期之间的差异(有几个函数可以做到这一点),并将这种差异影响到一个列表元素(我们将这个列表称为 Diff_list)。最后使用T_plot= [dtm.datetime.utcfromtimestamp(i) for i in Diff_List]。最后,plt.plot(T_plot,values) 将允许您在 x 轴上可视化日期。

你也可以使用 pandas 库

首先,根据文件parser=pd.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')中的日期类型定义日期解析

然后你阅读你的文件

tmp = pd.read_csv(your_file, parse_dates={'datetime': ['date', 'time']}, date_parser=parser, comment='#',delim_whitespace=True,names=['date', 'time', 'Values'])

data = tmp.set_index(tmp['datetime']).drop('datetime', axis=1)

如果您只需要表示小时 HH:MM:SS 而不是整个日期,您可以调整这些行。

注意:索引不会从 0 到 data.values.shape[0],但日期将用作索引。所以如果你想绘图,你可以做一个import matplotlib.pyplot as plt 然后plt.plot(data.index,data.Values)

【讨论】:

    【解决方案2】:

    您可以使用我为此目的开发的polt Python packagepolt 使用matplotlib 来同时显示来自多个来源的数据。

    创建一个脚本 adc_read.py 从您的 ADC 中读取值并将它们 prints 输出:

    import random, sys, time
    
    def read_adc():
        """
        Implement reading a voltage from your ADC here
        """
        # simulate measurement delay/sampling interval
        time.sleep(0.001)
        # simulate reading a voltage between 0 and 5V
        return random.uniform(0, 5)
    
    
    while True:
        # gather 100 readings
        adc_readings = tuple(read_adc() for i in range(100))
        # calculate average
        adc_average = sum(adc_readings) / len(adc_readings)
        # output average
        print(adc_average)
        sys.stdout.flush()
    

    哪个输出

    python3 adc_read.py
    # output
    2.3187490696344444
    2.40019412977279
    2.3702603804716555
    2.3793495215651435
    2.5596985467604703
    2.5433401603774413
    2.6048815735614004
    2.350392397280291
    2.4372325168231948
    2.5618046803145647
    ...
    

    然后可以将此输出将piped 转换为polt 以显示实时数据流:

    python3 adc_read.py | polt live
    

    标签可以通过添加元数据来实现:

    python3 adc_read.py | \
        polt \
            add-source -c- -o name=ADC \
            add-filter -f metadata -o set-quantity=voltage -o set-unit='V' \
            live
    

    polt documentation 包含有关进一步定制可能性的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-29
      • 2019-04-17
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多