Search code examples
rggplot2facet-wrapr-factor

How do I use ggplot and facet_wrap for plotting factor attributes in R


I have a dataset with a number of attributes that share common values (a price range, e.g. "£11-£20", "£21-£30"...) stored as factors. I am trying to plot a selection of these attributes using facet_wrap and having bar plots of the count for each with the price range on the x axis.

I can obtain the graphs I'd like individually, but I'd like to group these attributes as they are related. Example code is below:

dat <- data.frame(
  breakfast = factor(c("£11-£20","£11-£20","£21-30","£0-£10","£11-£20")),
  lunch = factor(c("£0-£10","£11-£20","£21-30","£11-£20","£21-30")),
  dinner = factor(c("£0-£10","£31-£40","£21-30","£11-£20","£21-30")),
  voucher_used = c(0,1,1,0,1)
)
View(dat)

ggplot(dat, aes(x = breakfast, fill = factor(voucher_used))) +
  geom_bar() +
  xlab("Breakfast") +
  ylab("No.") +
  labs(fill = "Voucher Used") # +
# facet_wrap(~ lunch)

Ideally I'd like to add the same plots for lunch and dinner alongside - is it possible or is there another better way to achieve the same result?

Many thanks


Solution

  • Yes, it is possible reshaping your data to long format using some tidyverse functions:

    library(ggplot2)
    library(dplyr)
    library(tidyr)
    #Data
    dat <- data.frame(
      breakfast = factor(c("£11-£20","£11-£20","£21-30","£0-£10","£11-£20")),
      lunch = factor(c("£0-£10","£11-£20","£21-30","£11-£20","£21-30")),
      dinner = factor(c("£0-£10","£31-£40","£21-30","£11-£20","£21-30")),
      voucher_used = c(0,1,1,0,1)
    )
    #Plot
    dat %>% pivot_longer(-voucher_used) %>%
      ggplot(aes(x = value, fill = factor(voucher_used))) +
      geom_bar() +
      xlab("Breakfast") +
      ylab("No.") +
      labs(fill = "Voucher Used") +
      facet_wrap(~ name,scales = 'free')+xlab('Var')
    

    Output:

    enter image description here