用每个条/组中的观测数量注释ggplot箱线图的分面。

3

我已经查看了其他类似的问题 (在 ggplot2 的面板上注释每个面板的观测数量),但没有找到关于如何对具有面板的箱线图中的单个条形进行注释的答案。

这是我创建箱线图的样本代码:

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))

ggplot(mms, aes(x=type, y=deliciousness, fill=type)) + 
   geom_boxplot(notch=TRUE)+
   facet_wrap(~ color,nrow=3, scales = "free")+
   xlab("")+
   scale_fill_manual(values = c("coral1", "lightcyan1", "olivedrab1"))+
   theme(legend.position="none")

以下是相应的图表:

enter image description here

现在,我想为每个颜色的每个facet单独注释组内的观察次数(peanut/regular),如我的图所示:

enter image description here

我已经使用dpyr对每种颜色和每个群组(花生/普通)的观察数量进行了总结,具体代码如下:

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

然而,我不知道如何将数据的总结添加到 ggplot 中。应该如何操作?
1个回答

4
尝试使用 dplyrggplot2 进行这种方法。 您可以使用 mutate() 构建标签,然后根据deliciousness的最大值格式化为只有一个值。之后,geom_text() 可以按照您想要的方式启用文本。以下是代码:
library(dplyr)
library(ggplot2)
#Data
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
mms %>% group_by(color,type) %>% mutate(N=n()) %>%
  mutate(N=ifelse(deliciousness==max(deliciousness,na.rm=T),paste0('n=',N),NA)) %>%
  ggplot(aes(x=type, y=deliciousness, fill=type,label=N)) + 
  geom_boxplot(notch=TRUE)+
  geom_text(fontface='bold')+
  facet_wrap(~ color,nrow=3, scales = "free")+
  xlab("")+
  scale_fill_manual(values = c("coral1", "lightcyan1", "olivedrab1"))+
  theme(legend.position="none")

输出:

输入图像描述


解释看起来不错。但是当我运行代码时,出现了以下错误:错误:n()只能在dplyr动词内使用。 - Olympia
@Olympia 请在一个新的会话中加载 dplyrggplot2 并首先使用您分享的数据进行测试。看起来您没有加载该软件包。 - Duck
@Olympia 太棒了!这也是一个很好的问题 :) - Duck
1
谢谢,如果您喜欢这个问题,请投票支持一下吧? :-) - Olympia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接