2017-04-23 38 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

注意:我已经添加指向图形,使其清楚在图上绘制哪些值。正如你所看到的,即使在该范围内的某些日子没有值,橙线也是直线。