2017-04-23 79 views
0

問題是繪製日期不均勻分佈的直線。使用系列值數據可以修正曲線問題,但會丟失時間軸(日期)。有沒有辦法來解決這個問題?繪製大熊貓系列線變成曲線

編輯:爲什麼不直接映射到X軸刻度日期:

0 -> 2017-02-17, 
1 -> 2017-02-20, 
... ? 

現在有似乎是橙色線12個蜱,但只有8個數據點。

import pandas as pd 
import matplotlib.pyplot as plt 

def straight_line(index): 
    y = [3 + 2*x for x in range(len(index))] 
    zserie = pd.Series(y, index=index) 

    return zserie 

if __name__ == '__main__': 

    start = '2017-02-10' 
    end = '2017-02-17' 
    index = pd.date_range(start,end) 

    index1 = pd.DatetimeIndex(['2017-02-17', '2017-02-20', '2017-02-21', '2017-02-22', 
       '2017-02-23', '2017-02-24', '2017-02-27', '2017-02-28',], 
       dtype='datetime64[ns]', name='pvm', freq=None) 

    plt.figure(1, figsize=(8, 4)) 

    zs = straight_line(index) 
    zs.plot() 

    zs = straight_line(index1) 
    zs.plot() 

    plt.figure(2, figsize=(8, 4)) 

    zs = straight_line(index1) 
    plt.plot(zs.values) 

Curvy line example Straight line with zs.values

+1

您是否試圖創建日期間不均勻間距的直線(x軸),或者您是否試圖使日期值像分類值一樣工作? – Craig

+1

第一塊情節中的橙色線似乎正是您正在尋找的情節。它有什麼問題? – ImportanceOfBeingErnest

+1

要得到一條直線,您必須調整x軸以與y軸相同的速率進行調整。這對於繪製彼此不同距離的日期並不適用。爲什麼你需要圖表對於數據是一條直線? – Aklys

回答

1

該圖被正確地處理該日期作爲連續變量。 index_1的日子應繪製在x座標爲17,20,21,22,23,24,27和28處。因此,橙線的圖形是正確的。

問題出在您計算straight_line()函數中的y值的方式。您將日期視爲僅僅是分類值並忽略日期之間的差距。線性迴歸計算不會這樣做 - 它會將日期視爲連續值。

要得到一條直線在你的示例代碼,你應該使用td = (index - index[0])轉換值index_1從絕對日期相對差異(返回大熊貓TimedeltaIndex),然後用天td爲的x值的計算。我已經展示瞭如何在下面的reg_line()功能做到這一點:

import pandas as pd 
import matplotlib.pyplot as plt 

def reg_line(index): 
    td = (index - index[0]).days #array containing the number of days since the first day 
    y = 3 + 2*td 
    zserie = pd.Series(y, index=index) 
    return zserie 

if __name__ == '__main__': 

    start = '2017-02-10' 
    end = '2017-02-17' 
    index = pd.date_range(start,end) 

    index1 = pd.DatetimeIndex(['2017-02-17', '2017-02-20', '2017-02-21', '2017-02-22', 
       '2017-02-23', '2017-02-24', '2017-02-27', '2017-02-28',], 
       dtype='datetime64[ns]', name='pvm', freq=None) 

    plt.figure(1, figsize=(8, 4)) 

    zs = reg_line(index) 
    zs.plot(style=['o-']) 

    zs = reg_line(index1) 
    zs.plot(style=['o-']) 

將會產生如下圖所示:

Regression Lines with Date Axis

注意:我已經添加指向圖形,使其清楚在圖上繪製哪些值。正如你所看到的,即使在該範圍內的某些日子沒有值,橙線也是直線。