2016-12-14 86 views
3

我是多级分析的初学者,并尝试了解如何使用base-R的绘图函数做图。我理解下面的fit的输出,但我对可视化很感兴趣。 df只是一些简单的测试数据:如何在不同颜色的多级分析中显示不同的级别

t <- seq(0, 10, 1) 
df <- data.frame(t = t, 
       y = 1.5+0.5*(-1)^t + (1.5+0.5*(-1)^t) * t, 
       p1 = as.factor(rep(c("p1", "p2"), 10)[1:11])) 

fit <- lm(y ~ t * p1, data = df) 

# I am looking for an automated version of that: 
plot(df$t, df$y) 
lines(df$t[df$p1 == "p1"], 
     fit$coefficients[1] + fit$coefficients[2] * df$t[df$p1 == "p1"], col = "blue") 
lines(df$t[df$p1 == "p2"], 
     fit$coefficients[1] + fit$coefficients[2] * df$t[df$p1 == "p2"] + 
     + fit$coefficients[3] + fit$coefficients[4] * df$t[df$p1 == "p2"], col = "red") 

应该知道,它必须包括p1,并且有两条线。
结果应该是这样的: Fit with two levels (interactions needs to be included)

编辑:预测est <- predict(fit, newx = t)给出了相同的结果拟合但我仍然不知道“如何群集”。

编辑2 @Keith:公式y ~ t * p1读数为y = (a + c * p1) + (b + d * p1) * t。对于“第一条蓝线”c, d都是零。

+0

将't'和'y'永远是一样的吗?你会总是有一个单一的因素列? –

+0

获得拟合值的更好方法是通过'predict()'。传递一个data.frame作为'newdata'来预测和惊讶。 –

+0

@KithithHughitt不,我真正的问题会更复杂,为简化的示例看[这里](http://stackoverflow.com/questions/40765869/analysis-using-linear-regression-based-on-subgroups)。这个问题的主要目的是“如何用正确的行数获得图表”。即使在这种简单的情况下('p1'只有2级!)我失败了;-) – Christoph

回答

3

这就是我该怎么做的。我还包括一个ggplot2版本的情节,因为我觉得它更适合我思考情节的方式。 该版本将计入p1中的级别数。如果您想补偿模型参数的数量,您只需调整构造xy的方式以包含所有相关变量。我应该指出,如果你省略了newdata的论点,那么将对提供给lm的数据集进行拟合。

t <- seq(0, 10, 1) 
df <- data.frame(t = t, 
       y = 1.5+0.5*(-1)^t + (1.5+0.5*(-1)^t) * t, 
       p1 = as.factor(rep(c("p1", "p2"), 10)[1:11])) 

fit <- lm(y ~ t * p1, data = df) 

xy <- data.frame(t = t, p1 = rep(levels(df$p1), each = length(t))) 
xy$fitted <- predict(fit, newdata = xy) 

library(RColorBrewer) # for colors, you can define your own 
cols <- brewer.pal(n = length(levels(df$p1)), name = "Set1") # feel free to ignore the warning 

plot(x = df$t, y = df$y) 
for (i in 1:length(levels(xy$p1))) { 
    tmp <- xy[xy$p1 == levels(xy$p1)[i], ] 
    lines(x = tmp$t, y = tmp$fitted, col = cols[i]) 
} 

enter image description here

library(ggplot2) 
ggplot(xy, aes(x = t, y = fitted, color = p1)) + 
    theme_bw() + 
    geom_point(data = df, aes(x = t, y = y)) + 
    geom_line() 

enter image description here