使用每个方面的观察数量注释ggplot2方面

Pet*_*ter 32 r ggplot2

可能重复:
创建与每个情节不同的注释GGPLOT2一个facet_wrap情节
在GGPLOT2到面的情节,添加文本与X轴日期

偶尔在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)
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 49

看起来之前已经问过这个问题,我最初看不出他们是如何联系的.我在这里回答这个问题,但是如果某人有更优雅的话,请不要接受.此外,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
Run Code Online (Sandbox Code Playgroud)

输出

  • 即使技术上是重复的,这个例子的优点是更简单,并且是解决方案的核心.OP的标题也更清晰. (3认同)
  • 谢谢 - 这提供了我在其他地方找不到的答案 (2认同)