Время печати и значение с плавающей запятой, используя python matplotlib из File - PullRequest
0 голосов
/ 17 декабря 2018

У меня есть текстовый файл со временем и значением с плавающей запятой.Я слышал, что можно построить эти две колонки с помощью matplotlib.Искал похожие темы, но не смог этого сделать.Мой код и данные -

import math
import datetime
import matplotlib
import matplotlib.pyplot as plt
import csv
with open('MaxMin.txt','r') as f_input:
csv_input = csv.reader(f_input, delimiter=' ',     skipinitialspace=True)
        x = []
        y = []
        for cols in csv_input:
            x = matplotlib.dates.date2num(cols[0])
            y = [float(cols[1])]
# naming the x axis 
plt.xlabel('Real-Time') 
# naming the y axis 
plt.ylabel('Acceleration (m/s2)') 
# giving a title to my graph 
plt.title('Accelerometer reading graph!')
# plotting the points 
plt.plot(x, y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
# function to show the plot 
plt.show()

И часть данных в MaxMin.txt

23:28:30.137 10.7695982757
23:28:30.161 10.4071263594
23:28:30.187 9.23969855461
23:28:30.212 9.21066485657
23:28:30.238 9.25117645762
23:28:30.262 9.59227680741
23:28:30.287 9.9773536301
23:28:30.312 10.0128275058
23:28:30.337 9.73353441664
23:28:30.361 9.75064993988
23:28:30.387 9.717339267
23:28:30.412 9.72736788911
23:28:30.440 9.62451269364

Я новичок в Python и на Python 2.7.15 в Windows 10 Pro (64 бит).Я установил NumPy, Scipy Scikit-учиться уже.Пожалуйста, помогите.

График окончательного вывода из полного набора данных.Спасибо @ ImportanceOfBeingErnest

Ответы [ 2 ]

0 голосов
/ 17 декабря 2018

Ошибка, которую вы сделали в первоначальной попытке, на самом деле довольно незначительна.Вместо добавления значений из цикла вы переопределяете их.Также вам нужно будет использовать datestr2num вместо date2num, потому что прочитанная строка еще не дата.

import matplotlib
import matplotlib.pyplot as plt
import csv
with open('MaxMin.txt','r') as f_input:
    csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
    x = []
    y = []
    for cols in csv_input:
        x.append(matplotlib.dates.datestr2num(cols[0]))
        y.append(float(cols[1]))
# naming the x axis 
plt.xlabel('Real-Time') 
# naming the y axis 
plt.ylabel('Acceleration (m/s2)') 
# giving a title to my graph 
plt.title('Accelerometer reading graph!')
# plotting the points 
plt.plot_date(x, y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
# function to show the plot 
plt.show()

enter image description here

Моя рекомендация о том, как сделать это проще, заключается в использовании numpy и преобразовании ввода в datetime.

from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt

x,y= np.loadtxt('MaxMin.txt', dtype=str, unpack=True)
x = np.array([datetime.strptime(i, "%H:%M:%S.%f") for i in x])
y = y.astype(float)

plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()

Относительно тиканья осей: для того, чтобы иметь тики каждые полсекунды, вы можете использовать MicrosecondLocator с интервалом 500000.

import matplotlib.dates

# ...

loc = matplotlib.dates.MicrosecondLocator(500000)
plt.gca().xaxis.set_major_locator(loc)
plt.gca().xaxis.set_major_formatter(matplotlib.dates.AutoDateFormatter(loc))
0 голосов
/ 17 декабря 2018

Вы можете использовать pandas для этого, сначала сохраните ваш файл в формате .csv:

import math
import datetime
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd #### import this library

df = pd.read_csv("path_to_file.csv", delimiter=' ', encoding='latin-1') 

x = df.ix[:,0]
y = df.ix[:,1]
# naming the x axis 
plt.xlabel('Real-Time') 
# naming the y axis 
plt.ylabel('Acceleration (m/s2)') 
# giving a title to my graph 
plt.title('Accelerometer reading graph!')
# plotting the points 
plt.plot(x, y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
# function to show the plot 
plt.show()

, если у первого столбца нет формата времени данных, вы можете преобразовать его в этот формат, например df.ix[:,0] = pd.to_datetime(df.ix[:,0]) и вы берете час, например:

df.ix[:,0] = df.ix[:,0].map(lambda x: x.hour)

Вывод после запуска кода был такой:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...