我这里有点麻烦,请帮帮我。我有这个数据
set.seed(4)
mydata <- data.frame(var = rnorm(100),
temp = rnorm(100),
subj = as.factor(rep(c(1:10),5)),
trt = rep(c("A","B"), 50))
和适合他们的模型
lm <- lm(var ~ temp * subj, data = mydata)
我想用格子绘制结果,并通过它们拟合回归线,用我的模型预测。为此,我使用了这种方法,由 D. Sarkar 概述了“用于高级用户的格子技巧”
temp_rng <- range(mydata$temp, finite = TRUE)
grid <- expand.grid(temp = do.breaks(temp_rng, 30),
subj = unique(mydata$subj),
trt = unique(mydata$trt))
model <- cbind(grid, var = predict(lm, newdata = grid))
orig <- mydata[c("var","temp","subj","trt")]
combined <- make.groups(original = orig, model = model)
xyplot(var ~ temp | subj,
data = combined,
groups = which,
type = c("p", "l"),
distribute.type = TRUE
)
到目前为止,一切都很好,但我还想为两种处理的数据点分配填充颜色trt=1
和trt=2
.
所以我写了这段代码,效果很好,但是在绘制回归线时,面板功能似乎无法识别类型......
my.fill <- c("black", "grey")
plot <- with(combined,
xyplot(var ~ temp | subj,
data = combined,
group = combined$which,
type = c("p", "l"),
distribute.type = TRUE,
panel = function(x, y, ..., subscripts){
fill <- my.fill[combined$trt[subscripts]]
panel.xyplot(x, y, pch = 21, fill = my.fill, col = "black")
},
key = list(space = "right",
text = list(c("trt1", "trt2"), cex = 0.8),
points = list(pch = c(21), fill = c("black", "grey")),
rep = FALSE)
)
)
plot
我还尝试在 中移动类型和分发类型panel.xyplot
,以及panel.xyplot
像这样对其中的数据进行子集化
plot <- with(combined,
xyplot(var ~ temp | subj,
data = combined,
panel = function(x, y, ..., subscripts){
fill <- my.fill[combined$trt[subscripts]]
panel.xyplot(x[combined$which=="original"], y[combined$which=="original"], pch = 21, fill = my.fill, col = "black")
panel.xyplot(x[combined$which=="model"], y[combined$which=="model"], type = "l", col = "black")
},
key = list(space = "right",
text = list(c("trt1", "trt2"), cex = 0.8),
points = list(pch = c(21), fill = c("black", "grey")),
rep = FALSE)
)
)
plot
但也没有成功。
谁能帮我将预测值绘制为一条线而不是点?