代码之家  ›  专栏  ›  技术社区  ›  Homer Jay Simpson

重新排序R中因子列的级别,使其在两个图中水平匹配

  •  0
  • Homer Jay Simpson  · 技术社区  · 7 月前

    我在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")
    
    
    

    导致

    enter image description here

    但我想重新排列var列,以便在likert和条形图中从上到下显示“否”级别,然后显示“是”级别。我如何在R中完成它?

    1 回复  |  直到 7 月前
        1
  •  1
  •   Gregor Thomas    7 月前

    ggplot中的Y轴从底部开始。所以,如果你想在顶部说“不”,它需要是你的最后一个因素水平,而不是你的第一个。

    ## Instead of this
    var = factor(var, levels = c("no", "yes"))
    ## use this
    var = factor(var, levels = c("yes", "no"))
    

    此外,一旦你的因子水平排列正确,就不要改变它们。 y = fct_reorder(var, n) 将按计数重新排序,这不是你想要的。