In [1]:
%matplotlib inline
import random
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
import statsmodels.formula.api as smf
sns.set_context("talk")
Anscombe's quartet
Anscombe's quartet comprises of four datasets, and is rather famous. Why? You'll find out in this exercise.
In [4]:
anascombe = pd.read_csv('data/anscombe.csv')
anascombe.head()
In [4]:
dataset x y
0 I 10 8.04
1 I 8 6.95
2 I 13 7.58
3 I 9 8.81
4 I 11 8.33
Part 1
For each of the four datasets...
- Compute the mean and variance of both x and y
- Compute the correlation coefficient between x and y
- Compute the linear regression line: y=β0+β1x+ϵy=β0+β1x+ϵ (hint: use statsmodels and look at the Statsmodels notebook)
In [5]:
print(anascombe.groupby('dataset').mean())
print(anascombe.groupby('dataset').var())
print(anascombe.x.corr(anascombe.y))
dataset x y dataset x y
I 9.0 7.500909 I 11.0 4.127269
II 9.0 7.500909 II 11.0 4.127629
III 9.0 7.500000 III 11.0 4.122620
IV 9.0 7.500909 IV 11.0 4.123249
0.81636624276147
y = anascombe.y
X = anascombe.x
X = sm.add_constant(X)
Linear = sm.OLS(y, X)
Linear = Linear.fit()
print(Linear.summary())
OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.636
Model: OLS Adj. R-squared: 0.623
Method: Least Squares F-statistic: 52.34
Date: Fri, 08 Jun 2018 Prob (F-statistic): 4.72e-08
Time: 19:25:11 Log-Likelihood: -50.810
No. Observations: 32 AIC: 105.6
Df Residuals: 30 BIC: 108.6
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
Intercept 3.2531 0.666 4.887 0.000 1.894 4.613
x 0.4843 0.067 7.234 0.000 0.348 0.621
==============================================================================
Omnibus: 1.104 Durbin-Watson: 1.995
Prob(Omnibus): 0.576 Jarque-Bera (JB): 0.593
Skew: 0.332 Prob(JB): 0.743
Kurtosis: 3.054 Cond. No. 30.9
==============================================================================
Part 2
Using Seaborn, visualize all four datasets.
hint: use sns.FacetGrid combined with plt.scatter
In [6]::
g = sns.FacetGrid(anascombe,col = 'dataset')
g = g.map(plt.scatter, "x", "y")
plt.show()
Out [6]: