我正在使用ggplot2
和facet_wrap
跟踪previous question来生成图形。下面是一个工作示例,其中许多内容都是根据@MrFlick提供的解决方案改编而成的。
require(data.table); require(ggplot2); require(purrr); require(dplyr)
N <- 1000 # Generate some data
DT <- NULL
models <- list() # list of fitted models. For simplicity i am using lm in this example
for(i in 1:6){
x <- rnorm(N)
y <- i*x + rnorm(N)
z <- rep(i,N)
i.DT <- data.table(cbind(x=x,y=y,z=z))
models[[i]] <- lm(y~x,i.DT)
DT <- rbind(DT,i.DT)
}
xrng <- 1.5*range(models[[length(models)]]$model$x)
yrng <- 1.5*range(models[[length(models)]]$model$y)
lines <- map_dfr(models, function(m) {
t <- data.frame(x=xrng, y=predict(m, data.frame(x=xrng)))
txrng <- xrng
tyrng <-t$y
while(!between(tyrng[1],yrng[1],yrng[2]) |
!between(tyrng[2],yrng[1],yrng[2])){
txrng <- txrng*0.9
t <- data.frame(x=txrng, y=predict(m, data.frame(x=txrng)))
tyrng <-t$y
}
return(t)
}, .id="z") # map lines from regression models
hlines <- map_dfr(models, function(m) {
t <- data.frame(x=xrng,y=rep(coef(m)[1],2))
return(t)
}, .id="z")
Slopes <- map_dfr(models, function(m) {
t <- data.frame(Intercept=coef(m)[1],Slope=coef(m)[2])
t$text <- paste0("Slope=",round(t$Slope,3))
return(t)
}, .id="z") # map text
my.plot <- ggplot(DT, aes(x=x, y=y,color=abs(y))) +
geom_point() + theme(legend.title=element_blank(),
legend.position=c(-0.14,0.85),
legend.text=element_text(size=10),
aspect.ratio=1) +
xlim(xrng) + ylim(yrng) +
facet_wrap(~z,nrow=2,ncol=3) + geom_line(color="red", data=lines) +
geom_line(color="black", data=hlines,linetype="dashed") +
geom_text(data=Slopes,aes(x=2, y=-20,label=text),
inherit.aes=FALSE)
my.plot
我是ggplot2
和facet_wrap
的新手,并且对了解如何指定其他详细信息和进一步自定义感兴趣。