%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.
anascombe = pd.read_csv('data/anscombe.csv')
anascombe.head()
輸出結果爲:
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)
print("the mean of x and y are:")
print(anascombe.groupby('dataset')['x','y'].mean())
print("the variance of x and y are:")
print(anascombe.groupby('dataset')['x', 'y'].var())
print("the correlation coefficient between x and y are:")
print(anascombe.groupby('dataset').corr())
print("the first linear regression line:")
lin_model_1 = smf.ols('y ~ x', anascombe.groupby('dataset').get_group('I')).fit()
print(lin_model_1.params)
print("the second linear regression line:")
lin_model_2 = smf.ols('y ~ x', anascombe.groupby('dataset').get_group('II')).fit()
print(lin_model_2.params)
print("the third linear regression line:")
lin_model_3 = smf.ols('y ~ x', anascombe.groupby('dataset').get_group('III')).fit()
print(lin_model_3.params)
print("the fourth linear regression line:")
lin_model_4 = smf.ols('y ~ x', anascombe.groupby('dataset').get_group('IV')).fit()
print(lin_model_4.params)
輸出結果爲:
Part 2
Using Seaborn, visualize all four datasets.
hint: use sns.FacetGrid combined with plt.scatter
sns.set(color_codes=True)
g = sns.FacetGrid(anascombe, col="dataset")
g.map(plt.scatter, "x", "y")
輸出結果爲: