Search code examples
rggplot2likert

Flip the text in facet rows in gglikert in R


I have the same simulated data as described here with the difference of the group 2 has elements of big text. I want to flip horizontally the text in facet rows to but without disappearing the facet col strip at the top.

How can I do it in R?

library(ggstats)
library(dplyr)
library(ggplot2)
likert_levels <- c(
  "Strongly disagree",
  "Disagree",
  "Neither agree nor disagree",
  "Agree",
  "Strongly agree"
)

df <-
  tibble(
    grouping = sample(c("A", "B", "C", "D"), 150, replace = TRUE),
    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(-grouping, ~ factor(.x, levels = likert_levels)))
df
gglikert(df, q1:q6, facet_cols = vars(grouping))
df_group <- df
df_group$group1 <- sample(c("category A", "category B","category C"), 150, replace = TRUE)
df_group$group2 <- sample(c("usa-new york", "usa-san fransisco", "usa-new orleans",
                            "united kingdom-stratford upon avon",
                            "south africa-port elizabeth",
                            "new zealand-upper hutt city"), 150, replace = TRUE)
gglikert(df_group,
         q3:q6,
         facet_cols = vars(group1),
         facet_rows = vars(group2),
         labels_size = 3
) +
  scale_x_continuous(
    labels = label_percent_abs(),
    expand = expansion(0, .2)
  )


enter image description here


Solution

  • You can achieve your desired result using

    + theme(strip.text.y = element_text(angle = 0))
    

    And as asked for in the comments, you can wrap the text by overwriting the default facet_grid layer and using label_wrap_gen() to wrap the strip text for the rows.

    gglikert(df_group,
      q3:q6,
      facet_cols = vars(group1),
      facet_rows = vars(group2),
      labels_size = 3
    ) +
      scale_x_continuous(
        labels = label_percent_abs(),
        expand = expansion(0, .2)
      ) + 
      facet_grid(
        cols = vars(group1),
        rows = vars(group2),
        labeller = labeller(
          .rows = label_wrap_gen(width = 20)
        )
      ) +
      theme(strip.text.y = element_text(angle = 0))
    

    enter image description here