我想制作一个散点图,其中包含不同群体和不同个体的连线。我制作的面板由我的组变量调整,组由我的个体变量决定。现在,我想在每个面板中添加图例(请参阅下面的代码)。在图中,我想在第一个面板中有GRP == 1的个体图例,第二个面板中的GRP == 2,依此类推。所有图例都位于它们所属面板的左上角。我该怎么编码?
library(lattice)
mydata <- data.frame(ID = rep(1: 20, each = 10),
GRP = rep(1: 4, each = 50),
x = rep(0: 9, 20))
mydata$y <- 1.2 * mydata$GRP * mydata$x +
rnorm(nrow(mydata), sd = mydata$GRP)
xyplot(y~ x | factor(GRP), data = mydata,
groups = ID,
type = "b",
as.table = T,
layout = c(2, 2),
panel = panel.superpose,
panel.groups = function (x, y, ...) {
panel.xyplot(x, y, ...)
}
)
答案 0 :(得分:1)
尝试这样的事情。请注意,subset命令位于xyplot的data语句中。这是故意的。如果将子集作为xyplot参数调用,那么这些图将在每个图中显示所有20个标签。
library(lattice)
mydata <- data.frame(ID = rep(1:20, each = 10), GRP = rep(1:4, each = 50), x = rep(0:9, 20))
mydata$y <- 1.2 * mydata$GRP * mydata$x + rnorm(nrow(mydata), sd = mydata$GRP)
i=1; j=1
for(grp in 1:4) {
a <- xyplot(y~x|factor(GRP), data=subset(mydata, GRP==grp),
groups = factor(ID),
type = "b",
auto.key=list(columns=4,space="inside")
)
print(a, split=c(i,j,2,2), more=T)
i=i+1; if(i>2){i=1;j=j+1} # basically, tell the plots which quadrant to go in
}