r - 如何使用GGPLOT Facet创建4x4散点图

标签 r ggplot2

我有这样的数据框:

library(ggplot2)
d.405 <- data.frame(abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),type="405")
d.409 <- data.frame(abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),type="409")
all <- rbind(d.405,d.409)
colnames(all) <- c("401","402","403","404","type");
all

我要做的是使用GGPLOT构面创建4x4绘图。这样
它看起来像这样:

最好的方法是什么?

我坚持下面的代码:
library("reshape2");
library(plyr)
allM <- melt(all, id.vars = "type")
allList <- split(allM$value, interaction(allM$type, allM$variable))
allComb <- unlist(lapply(c(1, 3), function(x) lapply(c(2 ,4), function(y)    do.call(cbind,allList[c(x,y)]))), recursive=FALSE)



allNew <- do.call(rbind,
        lapply(allComb, function(x) {
            tmp <- as.data.frame(x)
            tmp <- (within(tmp, {xval<-names(tmp)[1];
                                 yval<-names(tmp)[2]}))
            names(tmp)[1:2] <- c("405","409")
            tmp}))



head(allNew)

p <- ggplot(allNew, aes(x = 405, y = 409)) + geom_smooth(method = "lm")  +  geom_point() + facet_grid(yval ~ xval)
# Calculate correlation for each group
cors <- ddply(allNew, .(yval, xval), summarise, cor = round(cor(405, 409), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor,sep="")), x=0.5, y=0.5)
p

最佳答案

library(ggplot2)
d.405 <- data.frame(abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),type="405")
d.409 <- data.frame(abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),abs(rnorm(30)),type="409")
all <- rbind(d.405,d.409)
colnames(all) <- c("401","402","403","404","type")

library("reshape2");
allM <- melt(all, id.vars = "type")


combis <- expand.grid(levels(allM$variable),levels(allM$variable))

plotdat <- lapply(seq_len(nrow(combis)),function(i) cbind(allM[allM$variable==combis[i,1] & allM$type=="405",],
                                               allM[allM$variable==combis[i,2] & allM$type=="409",c("type","variable","value")]))
plotdat <- do.call(rbind,plotdat)
names(plotdat) <- c("type.x","var.x","x","type.y","var.y","y")
plotdat$var.x <- paste("x:",plotdat$var.x)
plotdat$var.y <- paste("y:",plotdat$var.y)

library(plyr)
cors <- ddply(plotdat,.(var.x,var.y),summarize,cor=format(signif(cor(x,y),2),scientific=-2))
cors$x <- 2.2
cors$y <- 2.5

p <- ggplot(plotdat,aes(x=x,y=y)) + 
  geom_point() + 
  geom_smooth(method="lm") +
  geom_text(data=cors,aes(label=paste("r =",cor))) +
  facet_wrap(~var.y*var.x,ncol=4) +
  xlab("405") + ylab("409")


print(p)

关于r - 如何使用GGPLOT Facet创建4x4散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16977010/

相关文章:

r - 找到最大长度为 "chain"的数字递增对

r - 如何在 R 中的 2 个列表的元素之间应用函数?

r - transition_time 带有阴影标记,仅用于一个几何体/层

r - ggplot 的 Shiny 切割顶部

r - 如何在 ggplot 中对轴标签进行分层?

r - R "undefined columns selected"中的错误

r - 均值的条件计算

r - 使用 ggplot 将科学计数法转换为小数

r - 向图例元素组添加注释和段

r - 未指定美学时使用 geom_sf 绘制图例