[英]How to plot date and time in X axis against Y value (Python)
Data 数据
2018.05.01,01:15,1.206870,1.206920,1.206870,1.206920,0
2018.05.01,01:16,1.206910,1.206910,1.206810,1.206820,0
Code 码
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
data1 = pd.read_csv('DAT_MT_EURUSD_M1_201805.csv')
date, time, closep, highp, openp = np.loadtxt(data1,
delimiter=',',
unpack = True,
dtype=float,
converters ={0: bytespdate2num('%Y%m%d%H:%M')})
At the end have an error 最后有一个错误
ValueError: time data u'2018.05.01' does not match format '%Y%m%d%H:%M'
ValueError:时间数据u'2018.05.01'与格式'%Y%m%d%H:%M'不匹配
It seems like i have to write a converter function to fit the proper date format, but I don't know how. 看来我必须编写一个转换器函数以适合正确的日期格式,但我不知道如何。
Please suggest. 请提出建议。
Just change the format to %Y.%m.%d
should do the trick, you're missing the dots in between. 只需将格式更改为
%Y.%m.%d
,因为它们之间缺少点。
If not you can also try dateutil
which parses most of the date formats for you: 如果没有,您也可以尝试使用
dateutil
为您解析大多数日期格式:
import dateutil
dateutil.parser.parse(my_date_str)
Your date and time are separated by a comma, which you are splitting on, so you are getting incorrect results. 您的日期和时间用逗号分隔,您正在使用逗号分隔,因此您得到的结果不正确。 You should pre-format your file to remove that first comma:
您应该预先格式化文件以删除第一个逗号:
data = []
with open('test.txt') as f:
for line in f:
data.append(line.replace(',', ' ', 1))
with open('test.txt', 'w') as outf:
outf.write(''.join(data))
# 2018.05.01 01:15,1.206870,1.206920,1.206870,1.206920,0
# 2018.05.01 01:16,1.206910,1.206910,1.206810,1.206820,0
Which can then easily be parsed into a time using pandas (which you're already using): 然后可以使用熊猫(您已经在使用)轻松地将其解析为某个时间:
df = pd.read_csv('test.txt', header=None)
pd.to_datetime(df[0])
0 2018-05-01 01:15:00
1 2018-05-01 01:16:00
Name: 0, dtype: datetime64[ns]
You can directly ask pd.read_csv()
to parse the date and time with the parse_date
keyword argument: 您可以直接要求
pd.read_csv()
使用parse_date
关键字参数来解析日期和时间:
import pandas as pd
import matplotlib.pyplot as plt
# Read data AND parse time stamps (date + time) given by columns 0 and 1
data = pd.read_csv('data.csv', sep=',', header=None, parse_dates=[0, 1])
# Plot and save figure
plt.plot(data[[1]], data[[2, 3, 4, 5]])
plt.savefig('pandas_plot.png')
Given the two lines of data you provided (that I stored in the data.csv
file), this script produces the following figure (where you can actually see your data sampled at two different dates): 给定您提供的两行数据(我存储在
data.csv
文件中),此脚本将产生下图(实际上您可以在两个不同的日期看到采样的数据):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.