R 如何使用不同的颜色在多级分析中显示不同的级别

R 如何使用不同的颜色在多级分析中显示不同的级别,r,plot,lm,R,Plot,Lm,我是一名多级分析的初学者,并试图了解如何使用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]))

我是一名多级分析的初学者,并试图了解如何使用
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")

t我就是这样做的。我还包括了plot的
ggplot2
版本,因为我发现它更适合我思考plot的方式。 此版本将说明
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])
}

是否
t
y
始终相同?您是否总是有一个单因素列?获得拟合值的更好方法是通过
predict()
。将data.frame传递为
newdata
,以便预测和惊奇。@KeithHughitt不,我真正的问题要复杂得多,举个简单的例子。这个问题的主要目的实际上是“如何获得具有正确行数的图形”。即使在这个简单的情况下(
p1
只有两个级别!)我也失败;-)@RomanLuštrik查看我的编辑。我知道
predict
(虽然我不明白为什么它比
lm
好),但这里的问题是如何获得“正确的行数”。另见上面的评论。这可能是一个愚蠢的问题,但我无法理解。什么是“集群”?没有像
newx
这样的参数。我不明白这里的行数有什么问题?行数应与p1中的系数级别相同,对吗?
library(ggplot2)
ggplot(xy, aes(x = t, y = fitted, color = p1)) +
  theme_bw() +
  geom_point(data = df, aes(x = t, y = y)) +
  geom_line()