Проблемы с Matplotlib при преобразовании строки в читаемый формат даты не могут быть скомпилированы - PullRequest
0 голосов
/ 10 сентября 2018

У меня проблема с программированием в реальном времени - изменение графика и гистограммы из CSV-файла, в котором сохраняются данные - запись содержит дату («% Y-% M-% D% H:% m:% S» ) и время, разделенное знаком табуляции '\ t'.

Однако я искал несколько итогов и документации и просто не могу это исправить. Ниже есть ссылки, с которыми я сталкивался:

  1. https://github.com/etsy/skyline/issues/123
  2. Как исправить AttributeError: у объекта 'Series' нет атрибута 'find'?
  3. https://docs.python.org/3.4/library/datetime.html
  4. Python / Numpy: проблемы с преобразованием типов в векторизации и элементе

Я не нашел ответа там и на других подобных веб-сайтах, включая итоговые данные sentdex на YT. Приведенный ниже код будет скомпилирован и использован на Raspberry Pi 3 B +, но он был создан на ОС Ubuntu на стандартном ПК - этот код прекрасно работает там:

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]

1 Ответ

0 голосов
/ 11 сентября 2018

ОБНОВЛЕНИЕ:

Я думаю, что я только что преодолел эту проблему с помощью библиотеки потоков.Однако мне нужно выяснить, как их настроить вместе:

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...