rggplot2likert

Using ggplot in R for Likert scale values and grouping the y axis


i have a data frame in R with 2 columns A and Year as shown below :

set.seed(123)
A <- sample(1:5, 1000, replace = TRUE)
year <- sample(c(2019, 2020, 2021, 2022), 1000, replace = TRUE)
df <- data.frame(A, year)
 A year
1 3 2021
2 3 2022
3 2 2020
4 2 2021
5 3 2022
6 5 2021

I want to create a horizontal likert chart using ggplot but in the y axis to be grouped by Year and inside each Year to have the 5 percentages as each category. Also i want the colors of each category to be 1 red, 2 light red, 3 blue , 4 light green, 5 green.

How can i do it in R ?


Solution

  • ggplot(df) +
      geom_bar(aes(y = year, group = A, fill = as.factor(A)), position = position_stack(reverse = TRUE))+
      scale_fill_manual(
        values = c(
          `1` = "red", 
          `2` = "lightpink", 
          `3` = "skyblue", 
          `4` = "lightgreen", 
          `5` = "forestgreen"),
        name = "A")
    

    if you want to use percentages and a 100% filled bar instead of count:

    ggplot(df) +
      geom_bar(
        aes(y = year, group = A, fill = as.factor(A)), 
        position = position_fill(reverse = TRUE)
      )+
      labs(x = "percent")+
      scale_fill_manual(
        values = c(
          `1` = "red", 
          `2` = "lightpink", 
          `3` = "skyblue", 
          `4` = "lightgreen", 
          `5` = "forestgreen"),
        name = "A")+
      scale_x_continuous(
        breaks = seq(0, 1, 0.1), 
        labels = scales::label_percent()
        )