我在R中有一个模拟数据帧:
library(tidyverse)
library(ggstats)
library(patchwork)
set.seed(123)
likert_levels <- c(
"1" = "Very Dissatisfied",
"2" = "Dissatisfied",
"3" = "Neutral",
"4" = "Satisfied",
"5" = "Very Satisfied")
df = data.frame(
var = sample(c("yes", "no"), 50, replace = TRUE),
A= sample(likert_levels, 50, replace = TRUE)) %>%
mutate(across(everything(), as.factor)) %>%
as_tibble() %>%
mutate(across(-var, ~ factor(.x, levels = likert_levels)))
# starting plot (removed facets and ensured order of 'var' factor)
likert <- df %>%
mutate(id = row_number()) %>%
pivot_longer(-c(id,var), names_to="group") %>%
pivot_wider(names_from=var) %>%
gglikert(c(df$var)) # removed facet_rows=vars(group)
# get the order of years according to n
df2 <- df %>%
mutate(id = row_number()) %>%
pivot_longer(-c(id, var), names_to = "group") %>%
count(group, var) %>%
mutate(var = factor(var, levels = c("no", "yes"))) %>%
arrange(var) %>%
select(var) %>%
distinct()
likert$data <- likert$data %>%
mutate(.question = factor(.question, levels = c("no", "yes")))
# create the barplot (removed facets and ensured order of 'var' factor)
bar <- df %>%
mutate(id = row_number()) %>%
pivot_longer(-c(id, var), names_to = "group") %>%
count(group, var) %>%
mutate(var = factor(var, levels = c("no", "yes"))) %>% # ensure 'no' comes first
ggplot(aes(x = n, y = fct_reorder(var, n))) +
geom_col() +
geom_label(aes(label = n),
color = "white", hjust = 1,
fill = NA, label.size = 0) +
labs(y = NULL) + # removed facet_wrap
likert$theme
# plot them side by side
likert + bar + plot_layout(widths = c(0.8, 0.2), guides = "collect") &
theme(legend.position = "bottom")
导致
但我想重新排列var列,以便在likert和条形图中从上到下显示“否”级别,然后显示“是”级别。我如何在R中完成它?