我有一个带有时间和浮点值的文本文件。我听说可以使用matplotlib绘制这两列。搜索了相似的线程,但无法实现。我的代码和数据是-
return $result;
以及MaxMin.txt中的部分数据
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()
我是Python和Windows 10 pro(64位)中python 2.7.15的初学者。我已经安装了numpy,scipy scikit-learn。请帮忙。
Final Output Graph from complete Data Set. Thanks @ ImportanceOfBeingErnest
答案 0 :(得分:3)
您可以使用熊猫来实现此目的,首先以.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)
运行代码后的输出如下:
答案 1 :(得分:1)
您在原始尝试中犯的错误实际上很小。您无需重新定义循环中的值,而是重新定义它们。
另外,您还需要使用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()
我对如何简化此操作的建议是使用numpy并将输入转换为日期时间。
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))