Search code examples
rdataframeggplot2

Exclude proportions from Likert chart and change the theme in gglikert() function in R


I have a data frame called df which has Likert scale values:

library(tidyverse)
likert_levels <- c(
  "Strongly disagree",
  "Disagree",
  "Neither agree nor disagree",
  "Agree",
  "Strongly agree"
)
set.seed(42)
df <-
  tibble(
    q1 = sample(likert_levels, 150, replace = TRUE),
    q2 = sample(likert_levels, 150, replace = TRUE, prob = 5:1),
    q3 = sample(likert_levels, 150, replace = TRUE, prob = 1:5),
    q4 = sample(likert_levels, 150, replace = TRUE, prob = 1:5),
    q5 = sample(c(likert_levels, NA), 150, replace = TRUE),
    q6 = sample(likert_levels, 150, replace = TRUE, prob = c(1, 0, 1, 1, 0))
  ) %>%
  mutate(across(everything(), ~ factor(.x, levels = likert_levels)))%>%
  ggstats::gglikert(.)
df

resulting to a plot like the following : enter image description here

I want:

  1. to show the percentages of the the middle level and the two total left and right.For example in the attached picture in the first line for q1 to display only the 49% 12% and 39%.

  2. Also I do not want to display the lines in the background theme.I want to have it complete white.

  3. in the x axis to display the 100% - 50% - 0% -50% - 100%

How can I do these in R using ggplot2 ?


Solution

  • library(tidyverse)
    
    set.seed(42)
    
    likert_levels <- c(
      "Strongly disagree",
      "Disagree",
      "Neither agree nor disagree",
      "Agree",
      "Strongly agree"
    )
    
    df <-
      tibble(
        q1 = sample(likert_levels, 150, replace = TRUE),
        q2 = sample(likert_levels, 150, replace = TRUE, prob = 5:1),
        q3 = sample(likert_levels, 150, replace = TRUE, prob = 1:5),
        q4 = sample(likert_levels, 150, replace = TRUE, prob = 1:5),
        q5 = sample(c(likert_levels, NA), 150, replace = TRUE),
        q6 = sample(likert_levels, 150, replace = TRUE, prob = c(1, 0, 1, 1, 0))
      ) %>%
      mutate(across(everything(), ~ factor(.x, levels = likert_levels)))
    
    breaks <- seq(-1, 1, 0.5)
    
    gg <- df %>% 
      ggstats::gglikert() +
      # re-label x-axis
      scale_x_continuous(
        breaks = breaks,
        labels = paste0(100 * abs(breaks), "%"),
        limits = c(-1, 1)
      ) + 
      # remove vertical grid lines
      theme(
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank()
      )
    #> Scale for x is already present.
    #> Adding another scale for x, which will replace the existing scale.
    
    # disassemble
    g <- ggplot_build(gg)
    
    # only keep neutral labels
    g$data[[2]] <- g$data[[2]] %>% 
      mutate(label = if_else(fill == "#F5F5F5", label, ""))
    
    # move total labels
    g$data[[3]] <- g$data[[3]] %>% 
      mutate(x = if_else(x < 0, -1, 1))
    
    # reassemblee
    gg <- ggplot_gtable(g)
    
    # plot
    plot(gg)
    

    Created on 2024-08-29 with reprex v2.1.1