Search code examples
pythonpython-3.xpandasmatplotlibsklearn-pandas

Converting list of arrays for plotting using matplotlib in Python


I'm trying to produce rolling regressions using the sklearn package and subsequently plot them in using matplotlib.

I've been able to produce the rolling regression coefficients, but appending output is resulting in a 3-D list that I'm having difficulty plotting.

Code below is giving the following error:

ValueError: x and y can be no greater than 2-D, but have shapes (130,) and (130, 1, 5)

rCoeff = []
lm = sk_l.LinearRegression()
for iS in range(1, len(y)-(rollingN-1)):

    iE = iS+(rollingN-1)
    subX = X[iS:iE]
    suby = y[iS:iE]

    lm.fit(subX,suby)
    rCoeff.append(lm.coef_)

x = df_cpf.loc[36:166,'Date']
plt.plot_date(x,rCoeff)

Is there a method for 'squeezing' the 3D list into 2 dimensions, or some other method, to allow this to plot?


Solution

  • Turns out using the extend() method rather than the append() method did the trick.

    rCoeff = []
    lm = sk_l.LinearRegression()
    for iS in range(1, len(y)-(rollingN-1)):
    
        iE = iS+(rollingN-1)
        subX = X[iS:iE]
        suby = y[iS:iE]
    
        lm.fit(subX,suby)
        rCoeff.extend(lm.coef_)
    
    x = df_cpf.loc[36:166,'Date']
    plt.plot_date(x,rCoeff)