我有一些使用matplotlib绘制的csv数据。我还在数据上方放置了一条趋势线(线性拟合)。我想扩展日期范围,以便我的趋势线可以预测未来6个月的数据。
我整天都在敲键盘。
CSV数据是
Date,Cash Bucks
29/07/2015,4010.14
22/08/2015,4471.09
26/08/2015,4685.6
我得到的无法预测未来的代码是
import csv
from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
filename = "statistics.csv"
f=open(filename, "rb")
reader = csv.reader(f)
headers = reader.next()
converters = [str.strip] + [float] * (len(headers) - 1) # get numeric values into floats
column = {}
for h in headers:
column[h] = []
for row in reader:
for h, v, conv in zip(headers, row, converters):
column[h].append(conv(v))
dates_list = [datetime.strptime(date, '%d/%m/%Y').date() for date in column['Date']]
f.close()
date_start = dates_list[0]
date_end = dates_list[-1] + timedelta(3*365/12)
# dates_list.append(date_end)
print dates_list
x1 = dates_list
x2 = mdates.date2num(x1)
y1 = column['Cash Bucks']
z=np.polyfit(x2,y1,1)
p=np.poly1d(z)
# Plot
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, axisbg='white')
# Plot actual data
plt.plot_date(x=x1, y=y1, fmt='o-')
plt.plot(x1,p(x2),'r--') #add trendline to plot
plt.title('Cash Bucks')
plt.ylabel('Cash Bucks')
plt.xlabel('Date')
plt.show()
如何增加日期范围和趋势线图以查看未来?
在绘制实际数据之后,需要将追加end_date
到x1
,然后x2
在绘制趋势线之前使用新的附加值进行重新制作。
因此,脚本的结尾将如下所示:
# Plot
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, axisbg='white')
# Plot actual data
plt.plot_date(x=x1, y=y1, fmt='o-')
# Now append the extra data
x1.append(date_end)
x2 = mdates.date2num(x1)
plt.plot(x1,p(x2),'r--') #add trendline to plot
plt.title('Cash Bucks')
plt.ylabel('Cash Bucks')
plt.xlabel('Date')
fig.autofmt_xdate() # This tidies up the x axis
plt.show()
我还fig.autofmt_xdate()
为您添加了x轴标签
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句