Search code examples
rggplot2geom-bar

ggplot geom_bar with separate grouped variables on the x axis


I have a data frame with five (5) columns of data. The first is a major grouping (cat1 or cat 2) and the other columns variables V1 to v4 are characteristics and their presence (1 = no and 2 = yes). I want to do bar plots of counts of the characteristics for each category and for each variable V1 to V4... preferably without changing the data frame around but ok if needed. Data script and plot that I would like to achieve from it are below. All variables are factors. The purpose is to see which characteristics appear dominant in Cat 1 and Cat 2. Any directions or links welcome.

cat = as.factor(c(1,1,1,1,1,2,2,2,2,2))
v1 =  as.factor(c(1,2,2,1,1,2,1,1,1,1))
v2 =  as.factor(c(1,1,2,2,1,1,2,2,1,1))
v3 =  as.factor(c(1,1,1,1,2,2,1,1,2,2))
v4 =  as.factor(c(1,2,2,2,2,1,2,2,1,1))
df = data.frame(cat,v1,v2,v3,v4)

enter image description here


Solution

  • One way would be reshaping the data, count yes and no in each category and plot :

    library(tidyverse)
    cust_labeller <- function(x) paste0("Cat = ", x)
    
    df %>%
      pivot_longer(cols = -cat) %>%
      count(cat, name, value) %>%
      mutate(value = recode(value, `1` = 'no', `2` = 'yes')) %>%
      ggplot() + aes(name, n, fill = value) + 
      geom_col(position = 'dodge') + 
      scale_fill_manual(values = c('blue', 'red')) + 
      facet_wrap(.~cat, labeller = as_labeller(cust_labeller),
                 strip.position="bottom") 
    

    enter image description here