首页 > 解决方案 > 无法编译将字符串转换为日期可读格式的 Matplotlib 问题

问题描述

我在实时编程时遇到问题 - 从保存数据的 csv 文件更改绘图和直方图 - 记录包含日期('%Y-%M-%D %H:%m:%S')和时间分隔,由制表符符号 '\t'。

但是,我正在搜索几个教程和文档,但根本无法修复它。下面,有我遇到的链接:

  1. https://github.com/etsy/skyline/issues/123
  2. 如何修复 AttributeError:“系列”对象没有“查找”属性?
  3. https://docs.python.org/3.4/library/datetime.html
  4. Python/Numpy:vectorize 和 item 中的类型转换问题

我在那里和其他类似网站上没有找到答案,包括 YT 上的 sentdex toturials。下面的代码将在 Raspberry Pi 3 B+ 上编译和使用,但它是在标准 PC 上的 Ubuntu OS 上创建的 - 此代码在那里完美运行:

import serial
import pandas as pd
import matplotlib.pyplot as plt
import csv
import datetime
import matplotlib.animation as animation




fig, axes = plt.subplots(nrows=1, ncols=2)
ax1, ax2 = axes.flatten()

def update(i):
     file_data = pd.read_csv("/home/pi/Desktop/score_board3", delimiter="\t", 
parse_dates=[0], header=None, usecols=[0, 1])
     ax1.clear()
     ax2.clear()
     ax1.plot(file_data[0].astype(float), file_data[1])
     ax2.hist([file_data[1],], bins='auto', histtype='bar', facecolor='#FF8C00', edgecolor='red')
     ax1.set_title('History')
     ax1.set_xlabel('Measurement time')
     ax1.set_ylabel('Reaction time [s]')
     ax2.set_title('Histogram')
     ax2.set_xlabel('Reaction time [s]')
     ax2.set_ylabel('Number of results')

ani = animation.FuncAnimation(fig, update, interval=1000)
plt.show()

arduino = serial.Serial('/dev/ttyACM0', 9600)
file = open ('/home/pi/Desktop/Noc_Naukowcow/score_board3', 'r+')


try:
    while True:
        file.read(1)
        new_score = arduino.readline()
        print(new_score)
        score = new_score.decode('utf-8').strip() + "\n"                 
        score_time = '{:%Y-%M-%D %H:%m:%S}'.format(datetime.datetime.now())
        file.write(score_time)
        file.write('\t')
        file.write(score)    
        file.flush()



except KeyboardInterrupt:
    print("KeyboardInterrupt has been caught.")



file.close()
scores_to_read.close()

编译该代码后,我收到很多错误发现:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
    return self.func(*args)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 280, in resize
    self.show()
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 351, in draw
    FigureCanvasAgg.draw(self)
  File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
    self.figure.draw(self.renderer)
  File "/usr/lib/python3/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/figure.py", line 1150, in draw
    self.canvas.draw_event(renderer)
  File "/usr/lib/python3/dist-packages/matplotlib/backend_bases.py", line 1815, in draw_event
    self.callbacks.process(s, event)
  File "/usr/lib/python3/dist-packages/matplotlib/cbook.py", line 549, in process
    proxy(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/cbook.py", line 416, in __call__
    return mtd(*args, **kwargs)
  File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 831, in _start
    self._init_draw()
  File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 1490, in _init_draw
    self._draw_frame(next(self.new_frame_seq()))
  File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 1512, in _draw_frame
    self._drawn_artists = self._func(framedata, *self._args)
  File "/home/pi/Desktop/kod testowy.py", line 16, in update
    parse_dates=[0], header=None, usecols=[0, 1])
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 678, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 440, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 787, in __init__
    self._make_engine(self.engine)
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 1014, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 1756, in __init__
    _validate_usecols_names(usecols, self.names)
  File "/home/pi/.local/lib/python3.5/site-packages/pandas/io/parsers.py", line 1134, in _validate_usecols_names
    "columns expected but not found: {missing}".format(missing=missing)
ValueError: Usecols do not match columns, columns expected but not found: [1]

标签: pythonmatplotlibraspberry-pi

解决方案


更新:

我想我刚刚使用线程库克服了这个问题。但是我需要弄清楚如何将它们设置在一起:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import serial
import datetime
import threading

fig, axes = plt.subplots(nrows=2, ncols=1)
ax1, ax2 = axes.flatten()

scores_to_read = serial.Serial ('/dev/ttyACM0', 9600)
file = open ("/home/pi/Desktop/Noc_Naukowcow/score_board.csv", 'r+')    

def update(i):
     file_data = pd.read_csv("/home/pi/Desktop/Noc_Naukowcow/score_board.csv", delimiter="\t", 
parse_dates=[0], header=None, usecols=[0, 1])
     ax1.clear()
     ax2.clear()
     ax1.plot(file_data[0],file_data[1])
     ax2.hist([file_data[1],], bins='auto', histtype='bar')
     #ax1.set_title('History')
     ax1.set_xlabel('Measurement time')
     ax1.set_ylabel('Reaction time [s]')
     #ax2.set_title('Histogram')
     ax2.set_xlabel('Reaction time [s]')
     ax2.set_ylabel('Number of results')
     ani = animation.FuncAnimation(fig, update, interval=1000)
     plt.plot()

def serial_port(file):
    file.read()
    new_score = scores_to_read.readline()
    print(new_score)
    score = new_score.decode('utf-8').strip() + "\n"
    score_time = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
    file.write(score_time)
    file.write('\t')
    file.write(score)
    file.flush()

thread1 = threading.Thread(target=serial_port, args=(file))
thread1.start()

推荐阅读