rggplot2likert

gglikert in R with grouping facets


i have a data frame called df that has 4 columns:1st year and the rest 3 A,B,C having likert values.

set.seed(123)
likert_levels <- c(
  "1" = "Very  Dissatisfied",
  "2" = "Dissatisfied",
  "3" = "Neutral",
  "4" = "Satisfied",
  "5" = "Very  Satisfied")
df = data.frame(
  year = sample(c(2023, 2022, 2020, 2018), 50, replace = TRUE),
  A = sample(likert_levels, 50, replace = TRUE),
  B = sample(likert_levels, 50, replace = TRUE),
  C = sample(likert_levels, 50, replace = TRUE))%>%
  mutate(across(everything(),as.factor))%>%
  as_tibble()%>%
  mutate(across(-year, ~ factor(.x, levels = likert_levels)))
df
> df
# A tibble: 50 × 4
   year  A                      B                      C                     
   <fct> <fct>                  <fct>                  <fct>                 
 1 2020  "Very \n Satisfied"    "Neutral"              "Very \n Dissatisfied"
 2 2022  "Satisfied"            "Very \n Dissatisfied" "Dissatisfied"        
 3 2022  "Very \n Satisfied"    "Very \n Satisfied"    "Satisfied"           
 4 2022  "Dissatisfied"         "Satisfied"            "Very \n Dissatisfied"
 5 2018  "Very \n Satisfied"    "Neutral"              "Neutral"             
 6 2018  "Satisfied"            "Satisfied"            "Neutral"             
 7 2018  "Very \n Dissatisfied" "Satisfied"            "Very \n Satisfied"   
 8 2020  "Dissatisfied"         "Satisfied"            "Dissatisfied"        
 9 2022  "Dissatisfied"         "Neutral"              "Satisfied"           
10 2018  "Dissatisfied"         "Neutral"              "Satisfied"           
# ℹ 40 more rows
# ℹ Use `print(n = ...)` to see more rows

i want to plot this data frame with each facet to be each column name and the rows of each facet the year. How can i succeed this using gglikert() function from ggstats in R ?

i want to have something like this :

enter image description here


Solution

  • Your data has the year in one column but the gglikert function needs these to be columns in wide format. So it's just a matter of tidying your data:

    mutate(df, id=row_number()) |>
      pivot_longer(-c(id, year), names_to="group") |>
      pivot_wider(names_from=year) |>
      gglikert(c(`2023`, `2022`, `2020`, `2018`), 
             facet_rows=vars(group))
    

    enter image description here