条件a ..count ..对faceting变量求和

Joh*_*ton 10 r ggplot2

我试图一个方面注释一个条形图,其中观察的百分比落入该桶中.这个问题与这个问题密切相关: 在分类变量的图表中显示%而不是计数,但是分面的引入引入了皱纹.相关问题的答案是使用stat_bin w/text geom,然后将标签构造如下:

 stat_bin(geom="text", aes(x = bins,
         y = ..count..,
         label = paste(round(100*(..count../sum(..count..)),1), "%", sep="")
         )
Run Code Online (Sandbox Code Playgroud)

这对于一个没有面子的情节很好.然而,对于facet,这个总和(.. count ..)是对整个观察集合的总结,而不考虑方面.下图说明了问题 - 请注意,在面板中百分比不等于100%.

在此输入图像描述

这里是上图的实际代码:

 g.invite.distro <- ggplot(data = df.exp) +
 geom_bar(aes(x = invite_bins)) +
 facet_wrap(~cat1, ncol=3) +
 stat_bin(geom="text", aes(x = invite_bins,
         y = ..count..,
         label = paste(round(100*(..count../sum(..count..)),1), "%", sep="")
         ),  
         vjust = -1, size = 3) +
  theme_bw() + 
scale_y_continuous(limits = c(0, 3000))
Run Code Online (Sandbox Code Playgroud)

更新:根据请求,这是一个重新产生问题的小例子:

df <- data.frame(x = c('a', 'a', 'b','b'), f = c('c', 'd','d','d'))
ggplot(data = df) + geom_bar(aes(x = x)) +
 stat_bin(geom = "text", aes(
         x = x,
         y = ..count.., label = ..count../sum(..count..)), vjust = -1) +
 facet_wrap(~f)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

San*_*att 11

更新 geom_bar要求stat = identity.

有时在ggplot调用之外获取摘要更容易.

df <- data.frame(x = c('a', 'a', 'b','b'), f = c('c', 'd','d','d'))

# Load packages
library(ggplot2)
library(plyr)

# Obtain summary. 'Freq' is the count, 'pct' is the percent within each 'f'
m = ddply(data.frame(table(df)), .(f), mutate, pct = round(Freq/sum(Freq) * 100, 1)) 

# Plot the data using the summary data frame
ggplot(data = m, aes(x = x, y = Freq)) + 
   geom_bar(stat = "identity", width = .7) +
   geom_text(aes(label = paste(m$pct, "%", sep = "")), vjust = -1, size = 3) +
   facet_wrap(~ f, ncol = 2) + theme_bw() +
   scale_y_continuous(limits = c(0, 1.2*max(m$Freq)))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述