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

如何使用facet_wrap绘制ggplot2,显示每组的百分比,而不是总体百分比?,r,ggplot2,percentage,facet,R,Ggplot2,Percentage,Facet,我想用facet_wrap绘制一个ggplot,它不显示实际的表格百分比,而是显示每组给定答案的百分比。我必须这样做,因为我想展示,对于每个小组来说,哪个答案是最有选择和最重要的。这些组的大小不同 示例数据: 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

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

示例数据:

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))
这是用于绘图的:

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

g最好事先计算百分比:

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)
这使得:

另请参见:
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)