2015-05-14 90 views
3

我想绘制一个ggplot with facet_wrap,它不会显示实际的表格百分比,而是显示每个组中给定答案的百分比。我必须这样做,因为我想表明,哪个答案是最有选择性的,对每个组最重要。这些组的尺寸不一样。如何使用facet_wrap绘制ggplot2,显示每个组的百分比,而不是总体百分比?

示例数据:

group <- c(rep(c("Group1"), times = 10),rep(c("Group2"), times = 6),rep(c("Group3"), times = 4)) 
choice <- c(rep(c("a","b","c"),length.out = 10), "a","a","a","a","b","c","b","b","b","c") 
df <- data.frame(cbind(group,choice)) 

这将是很好,如果我不能用整体prop.t,但prop.c在我的情节来展示,因为它表明的是重要的,例如该组的66.67% 2更喜欢选择a。

library(gmodels) 
CrossTable(choice, group, prop.chisq=FALSE, prop.t = TRUE, prop.c = TRUE, prop.r = FALSE, format = "SPSS") 

这是剧情:

library(ggplot2) 
g <- ggplot(df, aes_string(x="group", fill="group")) + 
      geom_bar(aes(y = (..count..)/sum(..count..)))+ 
      ylab("percent") 
g + facet_wrap(~ choice) 

This is how it looks so far

现在第一条显示:20%,20%,0%,而应该表现出40%,66.67%和0 %(组中每个人的百分比,谁给出了这个答案)。

第二栏应显示:30%,16.667%和75%。

和第三条:30%,16.667%和25%

谢谢您的帮助。

+0

另请参阅:http://stackoverflow.com/q/11026016/892313 –

回答

9

它可能会更好事先计算出百分比:

library(dplyr) 
dfl <- df %>% 
    group_by(group,choice) %>% 
    summarise(n=n()) %>% 
    group_by(group) %>% 
    mutate(perc=100*n/sum(n)) 

ggplot(dfl, aes(x=group, y=perc, fill=group)) + 
    geom_bar(stat="identity") + 
    ylab("percent") + 
    facet_wrap(~ choice) 

这给: enter image description here


另一个(可能更好)呈现数据的方式是通过组使用方面:

ggplot(dfl, aes(x=choice, y=perc, fill=choice)) + 
    geom_bar(stat="identity") + 
    ylab("percent") + 
    facet_wrap(~ group) 

这给出: enter image description here