【问题标题】:Annotate ggplot2 facets with number of observations per facet [duplicate]用每个方面的观察次数注释 ggplot2 方面[重复]
【发布时间】:2012-11-05 20:26:49
【问题描述】:

可能重复:
Creating a facet_wrap plot with ggplot2 with different annotations in each plot
Add text to a faceted plot in ggplot2 with dates on X axis

偶尔在 ggplot 中对数据进行分面时,我认为最好用落入每个方面的观察数量来注释每个方面。当刻面可能导致每个刻面的观察相对较少时,这一点尤其重要。

向该图的每个方面添加“n=X”的最佳/最简单方法是什么?

require(ggplot2)
mms <- data.frame(deliciousness = rnorm(100),
                  type=sample(as.factor(c("peanut", "regular")), 100, replace=TRUE),
                  color=sample(as.factor(c("red", "green", "yellow", "brown")), 100, replace=TRUE))


plot <- ggplot(data=mms, aes(x=deliciousness)) + geom_density() + facet_grid(type ~ color)

【问题讨论】:

标签: r ggplot2


【解决方案1】:

之前好像有人问过这个问题,但我一开始没看到它们是如何连接的。我在这里回答这个问题,但不接受它,以防有人有更优雅的东西。此外,n = foo 是一个很常见的情况,希望有人能从这个问题中得到一些用处,即使它有点重复。

require(ggplot2)
require(plyr)
mms <- data.frame(deliciousness = rnorm(100),
                  type=sample(as.factor(c("peanut", "regular")), 
                              100, replace=TRUE),
                  color=sample(as.factor(c("red", "green", "yellow", "brown")), 
                              100, replace=TRUE))


mms.cor <- ddply(.data=mms, 
                 .(type, color), 
                 summarize, 
                 n=paste("n =", length(deliciousness)))

plot <- ggplot(data=mms, aes(x=deliciousness)) + 
          geom_density() + 
          facet_grid(type ~ color) + 
          geom_text(data=mms.cor, aes(x=1.8, y=5, label=n), 
                    colour="black", inherit.aes=FALSE, parse=FALSE)

plot

【讨论】:

  • 谢谢 - 这提供了我在其他地方找不到的答案
  • 即使在技术上是重复的,这个例子的优点是更简单,并且是解决方案的核心。 OP 的标题也更清晰,恕我直言。
  • 有一个更简单的解决方案 - 避免必须定义 mms.cor。在geom_text 中,将数据定义为data = plyr::count(mms, vars = c("deliciousness"))。需要注意的是,我只对一个变量的方面进行了测试,而不是两个。
  • 谢谢,确实有帮助的问答!受@spops 评论的启发,我找到了一个可以在这个数据框上工作的解决方案,对两个变量进行分面,而不需要mms.cor:geom_text(data=plyr::count(mms, vars = c("type","color")), aes(x=1.8, y=5, label=paste0("N=",freq)), colour="black", inherit.aes=FALSE, parse=FALSE)
猜你喜欢
  • 1970-01-01
  • 2015-05-20
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2023-03-13
相关资源
最近更新 更多