Add trend line to pandas

后端 未结 2 789
自闭症患者
自闭症患者 2021-01-02 09:54

I have time-series data, as followed:

                  emplvl
date                    
2003-01-01  10955.000000
2003-04-01  11090.333333
2003-07-01  11157.0         


        
2条回答
  •  生来不讨喜
    2021-01-02 10:32

    In general you should create your matplotlib figure and axes object ahead of time, and explicitly plot the dataframe on that:

    from matplotlib import pyplot
    import pandas
    import statsmodels.api as sm
    
    df = pandas.read_csv(...)
    
    fig, ax = pyplot.subplots()
    df.plot(x='xcol', y='ycol', ax=ax)
    

    Then you still have that axes object around to use directly to plot your line:

    model = sm.formula.ols(formula='ycol ~ xcol', data=df)
    res = model.fit()
    df.assign(fit=res.fittedvalues).plot(x='xcol', y='fit', ax=ax)
    

提交回复
热议问题