方差分析,二元的,可以分为无交互效应和有交互效应。
代码如下:
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
plt.style.use("bmh")
import statsmodels.api as sm
from statsmodels.formula.api import ols
ybar = 87.5
alpha = 2.5
beta = 5
A = [1]*10 + [-1]*10
B = [1]*5 + [-1] * 5 + [1]*5 + [-1] * 5
y = np.array([ybar]*20) +np.array(A) * 2.5 +np.array(B) * 5 + np.random.normal(loc=0, scale=2, size=20)
df = pd.DataFrame({"group1":A, "group2":B, "y":y})
mod = ols("y~group1+group2+group1*group2", data=df).fit()
ano_table = sm.stats.anova_lm(mod)
ano_table
table = pd.pivot_table(df, index=['group1', 'group2'])
table
table2= table.reset_index()
fig, ax = plt.subplots()
y = table2['y']
xall = [1, 2]
ax.plot(xall[0], y[0], 'bo')
ax.plot(xall[0], y[1], 'bo')
ax.plot(xall[1], y[2], 'bo')
ax.plot(xall[1], y[3], 'bo')
ax.plot([1, 2], [y[0], y[2]], 'r')
ax.plot([1, 2], [y[1], y[3]], 'g')
table2
fig, ax = plt.subplots()
ax.plot(1, y[0], 'bo')
ax.plot(1, y[2], 'bo')
ax.plot(2, y[1], 'bo')
ax.plot(2, y[3], 'bo')
ax.plot([1, 2], [y[0], y[1]], 'r')
ax.plot([1, 2],[y[2], y[3]] , 'g')
##########################################
#################有交互作用
##########################################
y = np.array([ybar]*20) +np.array(A) * 2.5 +np.array(B) * 5 + np.array(A) * np.array(B) * 3 + np.random.normal(loc=0, scale=2, size=20)
df = pd.DataFrame({"group1":A, "group2":B, "y":y})
mod = ols("y~group1+group2+group1*group2", data=df).fit()
ano_table = sm.stats.anova_lm(mod)
ano_table
table = pd.pivot_table(df, index=['group1', 'group2'])
table
table2= table.reset_index()
fig, ax = plt.subplots()
y = table2['y']
xall = [1, 2]
ax.plot(xall[0], y[0], 'bo')
ax.plot(xall[0], y[1], 'bo')
ax.plot(xall[1], y[2], 'bo')
ax.plot(xall[1], y[3], 'bo')
ax.plot([1, 2], [y[0], y[2]], 'r')
ax.plot([1, 2], [y[1], y[3]], 'g')
table2
fig, ax = plt.subplots()
ax.plot(1, y[0], 'bo')
ax.plot(1, y[2], 'bo')
ax.plot(2, y[1], 'bo')
ax.plot(2, y[3], 'bo')
ax.plot([1, 2], [y[0], y[1]], 'r')
ax.plot([1, 2],[y[2], y[3]] , 'g')