R 条件a.计数。。刻面变量的求和

R 条件a.计数。。刻面变量的求和,r,ggplot2,R,Ggplot2,我试图用一个方面内落入该桶的观察值百分比来注释条形图。这个问题与这个问题密切相关: 但是镶嵌面的引入引入了皱纹。相关问题的答案是使用stat_bin w/文本geom,然后将标签构造为: stat_bin(geom="text", aes(x = bins, y = ..count.., label = paste(round(100*(..count../sum(..count..)),1), "%", sep="") ) 这适用于未分

我试图用一个方面内落入该桶的观察值百分比来注释条形图。这个问题与这个问题密切相关: 但是镶嵌面的引入引入了皱纹。相关问题的答案是使用stat_bin w/文本geom,然后将标签构造为:

 stat_bin(geom="text", aes(x = bins,
         y = ..count..,
         label = paste(round(100*(..count../sum(..count..)),1), "%", sep="")
         )
这适用于未分面的情节。然而,对于面,这个总和(…计数…)是对整个观察集合的总和,而不考虑面。下图说明了这个问题——请注意,在一个面板中,百分比总和并不是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))

g.invite.distro更新
geom\u 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)))

df一个有趣的问题,如果你给我们数据来重现你的错误,你就更有可能得到回复。对不起-应该这么做。现在有一个例子。我也遇到了这个问题,如果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)))