2013-09-28 8 views

Antwort

64
import numpy as np 
import matplotlib.pyplot as plt 

# sample data 
x = np.arange(10) 
y = 5*x + 10 

# fit with np.polyfit 
m, b = np.polyfit(x, y, 1) 

plt.plot(x, y, '.') 
plt.plot(x, m*x + b, '-') 

enter image description here

19

Ich bin zu scikits.statsmodels Teil. Hier ein Beispiel:

import statsmodels.api as sm 
import numpy as np 
import matplotlib.pyplot as plt 

X = np.random.rand(100) 
Y = X + np.random.rand(100)*0.1 

results = sm.OLS(Y,sm.add_constant(X)).fit() 

print results.summary() 

plt.scatter(X,Y) 

X_plot = np.linspace(0,1,100) 
plt.plot(X_plot, X_plot*results.params[0] + results.params[1]) 

plt.show() 

Der einzige schwierige Teil ist sm.add_constant(X) die ein Spalten von Einsen zu X, um einen konstanten Term zu erhalten hinzufügt.

 Summary of Regression Results 
======================================= 
| Dependent Variable:   ['y']| 
| Model:       OLS| 
| Method:    Least Squares| 
| Date:    Sat, 28 Sep 2013| 
| Time:      09:22:59| 
| # obs:       100.0| 
| Df residuals:     98.0| 
| Df model:      1.0| 
============================================================================== 
|     coefficient  std. error t-statistic   prob. | 
------------------------------------------------------------------------------ 
| x1      1.007  0.008466  118.9032   0.0000 | 
| const     0.05165  0.005138  10.0515   0.0000 | 
============================================================================== 
|       Models stats      Residual stats | 
------------------------------------------------------------------------------ 
| R-squared:      0.9931 Durbin-Watson:    1.484 | 
| Adjusted R-squared:   0.9930 Omnibus:     12.16 | 
| F-statistic:    1.414e+04 Prob(Omnibus):   0.002294 | 
| Prob (F-statistic):  9.137e-108 JB:      0.6818 | 
| Log likelihood:     223.8 Prob(JB):     0.7111 | 
| AIC criterion:     -443.7 Skew:      -0.2064 | 
| BIC criterion:     -438.5 Kurtosis:     2.048 | 
------------------------------------------------------------------------------ 

example plot

+2

Meine Figur sieht anders aus; die Linie ist am falschen Ort; über den Punkten – David

+2

@David: die Params-Arrays sind in der falschen Richtung. Versuchen: plt.plot (X_plot, X_plot * results.params [1] + results.params [0]). Oder, noch besser: plt.plot (X, results.fittedvalues) als die erste Formel annimmt, y linear x ist, die während hier gilt, ist nicht immer der Fall. – Ian

8

Eine andere Möglichkeit, es zu tun, mit axes.get_xlim():

import matplotlib.pyplot as plt 
import numpy as np 

def scatter_plot_with_correlation_line(x, y, graph_filepath): 
    ''' 
    http://stackoverflow.com/a/34571821/395857 
    x does not have to be ordered. 
    ''' 
    # Scatter plot 
    plt.scatter(x, y) 

    # Add correlation line 
    axes = plt.gca() 
    m, b = np.polyfit(x, y, 1) 
    X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100) 
    plt.plot(X_plot, m*X_plot + b, '-') 

    # Save figure 
    plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight') 

def main(): 
    # Data 
    x = np.random.rand(100) 
    y = x + np.random.rand(100)*0.1 

    # Plot 
    scatter_plot_with_correlation_line(x, y, 'scatter_plot.png') 

if __name__ == "__main__": 
    main() 
    #cProfile.run('main()') # if you want to do some profiling 

enter image description here

9

Eine einzeilige Version von this excellent answer die Linie der besten Anpassung zu zeichnen ist:

plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x))) 

Mit np.unique(x) anstelle von x wird der Fall behandelt, in dem x nicht sortiert ist oder doppelte Werte hat.

Der Anruf an poly1d ist eine Alternative zum Schreiben m*x + b wie in this other excellent answer.

+1

Hallo, meine x und y-Werte sind Arrays aus Listen umgewandelt mit 'numpy.asarray'. Wenn ich diese Codezeile hinzufüge, erhalte ich mehrere Zeilen in meinem Streudiagramm anstelle von einem. Was könnte der Grund sein? – artre

+1

@artre Danke, dass du das gemacht hast. Das kann passieren, wenn 'x' nicht sortiert ist oder doppelte Werte hat. Ich habe die Antwort bearbeitet. –

2
plt.plot(X_plot, X_plot*results.params[0] + results.params[1]) 

gegen

plt.plot(X_plot, X_plot*results.params[1] + results.params[0]) 
Verwandte Themen