r - 如何使用 GGPLOT 创建分面相关图

标签 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 y

all <- rbind(x,y)
colnames(all) <- c("name","val1","val2","type")

我想要做的是创建一个大致如下所示的多面 ggplot:

enter image description here

因此,上面的每个方面都是以下的相关图:
# Top left facet
subset(all,type=="x")$val1 
subset(all,type=="y")$val1

# Top right facet
subset(all,type=="x")$val1 
subset(all,type=="y")$val2

# ...etc..

但我坚持使用以下代码:
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 <- 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)

enter image description here

编辑:遵循OP的评论和编辑。这个想法是用所有四种组合重新创建数据,然后再创建方面。
# I consider the type in your previous data to be xx and yy
dat <- data.frame(val1 = c(rep(all$val1[all$type == "x"], 2), 
                           rep(all$val1[all$type == "y"], 2)), 
                  val2 = rep(all$val2, 2), 
                  grp1 = rep(c("x", "x", "y", "y"), each=10), 
                  grp2 = rep(c("x", "y", "x", "y"), each=10))

p <- ggplot(dat, aes(val1, val2)) + geom_point() + geom_smooth(method = "lm") + 
     facet_grid(grp1 ~ grp2)
cors <- ddply(dat, .(grp1, grp2), summarise, cor = round(cor(val1, val2), 2))
p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=1, y=-0.25)

enter image description here

关于r - 如何使用 GGPLOT 创建分面相关图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470463/

相关文章:

r - R中所有数字的中位数和所有字符的模式

Python 内存分析器绘图

javascript - 我怎样才能制作这样的情节?

r - ggplot2:如何将比例尺的图例与已解析的标签集成在一起?

r - ggplot2 添加跨越小平面边缘的注释

r - 团体票吗?

r - 聚合具有不同功能的多个变量

R plot 按频率改变线条粗细

python - 如何在 matplotlib plt.polar 图中设置轴限制

r - 更改 Sweave 中 ggplot2 图的大小,而不使文本/数字过大