使用时间作为xaxis值的Matplotlib实时图形

2024-06-25 23:57:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是想知道是否可以使用时间作为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'

我试过想办法把字符串转换成浮点数,但似乎做不到

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


Tags: 方法timedefcounteropenfloatlabelvoltage
2条回答

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

你也可以使用熊猫图书馆

首先,根据文件中的日期类型定义日期解析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)

如果只需要表示小时数而不是整个日期,则可以修改这些行。你知道吗

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

你可以使用我开发的polt Python package来实现这个目的。polt使用matplotlib同时显示来自多个源的数据。你知道吗

创建一个脚本adc_read.py,从ADC读取值并print将其输出:

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

polt plot window

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

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 plot window

polt documentation包含关于进一步定制可能性的信息。你知道吗

相关问题 更多 >