2015-11-05 76 views
2

我有一些csv數據,我用matplotlib繪製。我還把一個趨勢線(線性擬合)放在數據的頂部。我想延長日期範圍,以便我的趨勢線能夠預測未來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() 

如何提高日期範圍和趨勢線的情節看未來?

回答

2

在繪製實際數據之後,您需要將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軸標籤更好一點

enter image description here