简体   繁体   中英

ggplot: Percentages when using facet_wrap()

I have the following sample dataset:

library(tidyverse)

df <- data.frame(var1 = c("A", "B", "A", "B", "C", "A", "B", "A", "A", "B", "A"),
                 var2 = c("B", "B", "A", "B", "C", "A", "B", "B", "A", "A", "C"),
                 var3 = c("A", "B", "A", "C", "C", "A", "C", "C", "C", "C", "A"))

Now I'd like to plot the three variables as bar plots right next to each other:

# Absolute values
df %>% pivot_longer(cols=c(var1, var2, var3)) %>%
  ggplot(aes(value)) + geom_bar(fill='lightblue', color='black')  + facet_wrap(.~ name) + coord_flip()

I can easily do this when I need absolute numbers. But I dont know how to get the percentages for each variable (var1, var2, var3) separately , so that the values for each barplot sum up to 100%.

In the following plot the bars from all the three plots together sum up to 100%.

# Percentages (not what I want)
df %>% pivot_longer(cols=c(var1, var2, var3)) %>%
  ggplot(aes(value)) + geom_bar(aes(y = (..count..)/sum(..count..)*100), fill='lightblue', color='black')  +facet_wrap(.~name) + coord_flip()

Does anyone know how to do this?

Perhaps this?

df %>% 
  pivot_longer(cols = c(var1, var2, var3)) %>%
  count(name, value) %>%
  group_by(name) %>%
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = value, y = prop)) + 
  geom_col(fill = 'lightblue', color = 'black')  + 
  scale_y_continuous(labels = scales::percent) +
  facet_wrap(.~ name) + 
  coord_flip()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM