我在这里遇到一些麻烦,请帮助我。 我有这个数据
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)
我想用 lattice 绘制结果,并使用我的模型预测回归线。为此,我正在使用这种方法,概述了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
但也没有成功。
任何人都可以帮助我将预测值绘制为一条线而不是点吗?
答案 0 :(得分:6)
这可能是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
我不确定你的第一次尝试是怎么回事,但带有下标的那个没有用,因为x和y是subj数据的子集,所以使用基于{{1的向量对它们进行子集化不会像你想象的那样工作。试试这个。
combined
答案 1 :(得分:2)
仅在原始数据上使用panel.lmline
功能可能更容易:
xyplot(var ~ temp | subj,
data = orig,
panel = function(x,y,...,subscripts){
fill <- my.fill[orig$trt[subscripts]]
panel.xyplot(x, y, pch = 21, fill = my.fill,col = "black")
panel.lmline(x,y,col = "salmon")
},
key = list(space = "right",
text = list(c("trt1", "trt2"), cex = 0.8),
points = list(pch = c(21), fill = c("black", "grey")),
rep = FALSE)
)
答案 2 :(得分:2)
这可能是微不足道的,但您可以尝试:
xyplot(... , type=c("p","l","r"))
“p
”添加点,“l
”用虚线连接它们,“r
”适合您的数据线性模型。仅type="r"
将仅绘制回归线而不显示数据点。