Home > Back-end >  ggplot2: grouped bar graph with groupby results as one bar and the total as second bar
ggplot2: grouped bar graph with groupby results as one bar and the total as second bar

Time:11-23

I have a dataframe as follows

df = data.frame(col1 = c('a', 'b', 'c','d','e'), col2 = c(3,1,2,3,1), col3 = c('yes','yes','no','no','yes))

Essentially I would like a grouped bar chart where the first group is the number of times a value occurs in column2 and has a value of yes in column3, and the second bar is the total number of times the value occurs in column2, regardless of group.

hand drawn desired bar graph

CodePudding user response:

Use a grouped summary to compute yes and total, pivot to long, and map the pivoted column to fill:

library(tidyverse)

df %>%
  group_by(col2) %>%
  summarize(
    yes = sum(col3 == "yes"),
    total = n()
  ) %>%
  pivot_longer(
    yes:total,
    names_to = "response",
    values_to = "n"
  ) %>%
  mutate(response = fct_rev(response)) %>%
  ggplot()  
  geom_col(
    aes(col2, n, fill = response),
    position = "dodge"
  )  
  scale_y_continuous(limits = c(0, 3), expand = c(0, 0))  
  scale_fill_manual(values = c("#7570b3", "#1b9e77"))  
  theme_classic()

  • Related