我在这里遇到了一些麻烦,请帮助我.我有这些数据
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))
Run Code Online (Sandbox Code Playgroud)
和这个适合他们的模型
lm <- lm(var ~ temp * subj, data = mydata)
Run Code Online (Sandbox Code Playgroud)
我想用格子绘制结果并拟合回归线,用我的模型预测,通过它们.为此,我正在使用这种方法,概述了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
)
Run Code Online (Sandbox Code Playgroud)
到目前为止一切都很好,但我也想指定填充颜色的数据点两种治疗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
Run Code Online (Sandbox Code Playgroud)
我还试图在其中移动类型和分布类型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
Run Code Online (Sandbox Code Playgroud)
但也没有成功.
任何人都可以帮我把预测值绘制成一条线而不是点吗?
这可能是latticeExtra包的工作.
library(latticeExtra)
p1 <- xyplot(var ~ temp | subj, data=orig, panel=function(..., subscripts) {
fill <- my.fill[combined$trt[subscripts]]
panel.xyplot(..., pch=21, fill=my.fill, col="black")
})
p2 <- xyplot(var ~ temp | subj, data=model, type="l")
p1+p2
Run Code Online (Sandbox Code Playgroud)

我不确定你的第一次尝试是怎么回事,但是带有下标的那个没有用,因为x和y是subj的数据的子集,所以使用基于的向量对它们进行子集combined将无法正常工作你认为它会.试试这个.
xyplot(var ~ temp | subj, groups=which, data = combined,
panel = function(x, y, groups, subscripts){
fill <- my.fill[combined$trt[subscripts]]
g <- groups[subscripts]
panel.points(x[g=="original"], y[g=="original"], pch = 21,
fill = my.fill, col = "black")
panel.lines(x[g=="model"], y[g=="model"], 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)
)
Run Code Online (Sandbox Code Playgroud)