R 如何使用GGPLOT创建刻面相关图
我用以下方法创建了一个数据框R 如何使用GGPLOT创建刻面相关图,r,plot,ggplot2,R,Plot,Ggplot2,我用以下方法创建了一个数据框 library(ggplot2) x <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="x") y <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="y") # in reality the number of row could be larger than 10 for each x and
library(ggplot2)
x <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="x")
y <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type="y")
# in reality the number of row could be larger than 10 for each x and y
all <- rbind(x,y)
colnames(all) <- c("name","val1","val2","type")
但我一直在使用以下代码:
p <- ggplot(all, aes(val1, val2))+ geom_smooth(method = "lm") + geom_point() +
facet_grid(type ~ )
# Calculate correlation for each group
cors <- ddply(all, c(type ~ ), summarise, cor = round(cor(val1, val2), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=0.5, y=0.5)
p您的某些代码不正确。这对我很有用:
p <- ggplot(all, aes(val1, val2))+ geom_smooth(method = "lm") + geom_point() +
facet_grid(~type)
# Calculate correlation for each group
cors <- ddply(all, .(type), summarise, cor = round(cor(val1, val2), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=1, y=-0.25)
p由于您的数据格式不正确,因此必须先对其进行一些重塑,然后才能进行打印
首先,将数据重塑为长格式:
library(reshape2)
allM <- melt(all[-1], id.vars = "type")
创建所有组合的列表:
allComb <- unlist(lapply(c(1, 3),
function(x)
lapply(c(2 ,4),
function(y)
do.call(cbind, allList[c(x, y)]))),
recursive = FALSE)
allComb现在有一个额外的包ggpubr
可以使用stat\u cor()
函数准确地解决这个问题
library(tidyverse)
library(ggpubr)
ggplot(all, aes(val1, val2))+
geom_smooth(method = "lm") +
geom_point() +
facet_grid(~type) +
stat_cor()
不完全是。它应该创建2x2网格。请参见图纸中蓝色字体的组合。那么您希望在对角线上显示什么?上面写着“不需要绘制”-但它被绘制在你的图表中?我把它放在图表中只是为了在每个网格中显示,哪些值的组合用于相关性。@alexwhan,如果我理解正确,并且每个值都有一个单独的组,你必须重塑数据以获得所有4个x和y的组合,那么,用ncol=2进行包装可能吗?@alexwhan,你已经得到了答案,这个问题当时还不清楚。从你这里拿走答案是不公平的:)。类型与你想要的绘图图像有什么关系?有一个带有ggpairs函数的ggAlly包可能很有用。就目前而言,我很难看到您的示例数据和所需绘图之间的联系。尤其令人困惑的是,您提到的mpg和wt不在您的数据表中。我已经改正了。谢谢你指出。@neversaint只是出于好奇:你是怎么画的?您是否使用了软件应用程序?它是?
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("x", "y")
tmp}))
library(ggplot2)
p <- ggplot(allNew, aes(x = x, y = y)) +
geom_smooth(method = "lm") +
geom_point() +
facet_grid(yval ~ xval)
# Calculate correlation for each group
library(plyr)
cors <- ddply(allNew, .(yval, xval), summarise, cor = round(cor(x, y), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=0.5, y=0.5)
library(tidyverse)
library(ggpubr)
ggplot(all, aes(val1, val2))+
geom_smooth(method = "lm") +
geom_point() +
facet_grid(~type) +
stat_cor()