Search code examples
rggplot2bar-chartcategorical-data

Double bar plot to compare two categorical variables


I am trying to create a bar plot two categorical variables A1 A2 more less equal more less equal equal more .. and so on

I want a create a bar graph where the factor levels ("more", "less", "equal" etc) are on the x axis for both A1 and A2, and the y axis is the frequency

I used the following code for A1, but I can't figure out how to plot both A1 and A2 on the x-axis

ggplot(df, aes(x = A1)) + geom_bar() + theme(axis.text.x = element_text(angle = 45, hjust = 1))


Solution

  • You could achieve your desired result by reshaping you data to long format. Using some fake random data:

    library(ggplot2)
    library(tidyr)
    
    df_long <- df %>% 
      pivot_longer(c(A1, A2), names_to = "name", values_to = "value")
    
    head(df_long)
    #> # A tibble: 6 × 2
    #>   name  value
    #>   <chr> <chr>
    #> 1 A1    equal
    #> 2 A2    equal
    #> 3 A1    equal
    #> 4 A2    less 
    #> 5 A1    equal
    #> 6 A2    less
    
    ggplot(df_long) + 
      geom_bar(aes(x = value, fill = name), position = "dodge") + 
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
    

    DATA

    set.seed(123)
    df <- data.frame(
      A1 = sample(c("more", "less", "equal"), 100, replace = TRUE),
      A2 = sample(c("more", "less", "equal"), 100, replace = TRUE)
    )