如何使用 facet_wrap 绘制 ggplot2,显示每个组的百分比,而不是总体百分比?

How to draw a ggplot2 with facet_wrap, showing percentages from each group, not overall percentages?

我想用 facet_wrap 绘制一个 ggplot,它不显示实际的 table 百分比,而是显示每个组中给定答案的百分比。我必须这样做,因为我想展示哪个答案对每个组来说都是最被选中和最重要的。这些组的大小不同。

示例数据:

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 来显示在我的情节中,那就太好了,因为显示很重要,例如第 2 组的 66.67%更喜欢选项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)

现在第一个栏显示:20%、20%、0%,但应该显示 40%、66.67% 和 0%(组中每个人给出此答案的百分比)。

第二个柱应显示:30%、16.667% 和 75%。

第三个柱:30%、16.667% 和 25%

感谢您的帮助。

最好事先计算一下百分比:

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)

这给出:


另一种(可能更好)呈现数据的方式是按组使用分面:

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

这给出: