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

时间:2012-11-05 20:26:50

标签: r ggplot2

  

可能重复:
  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)

1 个答案:

答案 0 :(得分:47)

之前有人问过这个问题,我最初没看到他们是如何联系的。我在这里回答这个问题,但是如果某人有更优雅的话,请不要接受。此外,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

The output