使用文件中的python matplotlib打印时间和浮点值

使用文件中的python matplotlib打印时间和浮点值,python,file,datetime,matplotlib,plot,Python,File,Datetime,Matplotlib,Plot,我有一个带有时间和浮点值的文本文件。我听说可以使用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=' ', sk

我有一个带有时间和浮点值的文本文件。我听说可以使用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和Windows10Pro(64位)中Python 2.7.15的初学者。我已经安装了numpy、scipy和scikit。请帮忙


您可以使用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)
运行代码后的输出如下所示:


您在最初尝试中犯的错误实际上很小。您重新定义了循环中的值,而不是附加这些值。 您还需要使用
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并将输入转换为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()

关于轴的滴答声:为了每半秒滴答一次,您可以使用间隔为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))

先生,我是初学者。因此,多做一点解释会非常有帮助。我给出了文本文件中的一些示例数据,因为我不知道它们现在是什么格式(string/number/Date)。我想用干净的数据标签绘制这些数据(文本文件中总共有900个数据)。这个答案假设OP使用的是
panda
,而不是。我已经安装了panda,如果它解决了问题,我不介意使用它。现在正在绘制图表,谢谢@Rodwan。但是X轴值无法读取。您希望在X轴上显示什么?这和我展示的输出一样吗?@user32185我上面的评论指的是,它根本没有提到熊猫,只是用得很清楚。代码不错。运行良好,但当记录数超过100时,仅显示三个X轴值。不幸的是,每个文件平均有2000-5000条记录。如何控制差距(如果我缩放曲线,它会自动调整,但在正常视图中,至少需要X轴上的每秒值。这方面有什么帮助吗?@importanceofbeingernese很难获得比自动标记数更多的自动标记。如果使用自定义标记器,可以在秒范围内获得更多的标记,但它会放大绘图失败。是否需要放大?(如果不需要,显示在x轴上的值的范围是什么,即第一个和最后一个基准?)您可以在我的OP中查看示例数据。我不知道正确的范围应该是什么,但0.5秒的间隔就可以了。不,绝对不需要缩放图形。我试图查看x轴标签是如何随此自动更改的。我还在这里的注释中提供了完整文件的驱动链接。您可以将整个数据请从中取出并查看。尝试使用以下内容:-自定义格式myFmt=mdates.DateFormatter(“%H:%M:%S.%f”)plt.gca().xaxis.set_major_formatter(myFmt)不需要缩放,这很容易。我更新了答案。几乎达到了我想要的90%。在毫秒内将5更改为10以获得秒。但是是否可以以HH:MM:SS格式显示,并在秒后抑制5个零。我已上载了图表。