【问题标题】:Ordering ggplot columns using reorder not working使用重新排序对 ggplot 列进行排序不起作用
【发布时间】:2021-07-08 14:39:23
【问题描述】:

我有如下所示的代码,我现在想在基于n 订购条形图时绘制obstacles (x) 和n (y),所以我继续执行以下操作:

library(tidyverse)
move_obstacles = tibble::tribble(
  ~move_approach,                           ~obstacle, ~n,
  "Relocate", "Distance from business activities", 1L,
  "Relocate",                      "No customers", 1L,
  "Relocate",                       "No services", 1L,
  "Upgrade Existing",                      "Cost of move", 4L,
  "Upgrade Existing", "Distance from business activities", 6L,
  "Upgrade Existing",                       "Higher rent", 1L,
  "Upgrade Existing",                      "Higher taxes", 2L,
  "Upgrade Existing",                      "No customers", 6L,
  "Upgrade Existing",                       "No services", 3L
) %>%
  ggplot(aes(reorder(obstacle,n),n)) +
  geom_col() +
  theme_bw() + 
  coord_flip() +
  xlab(NULL) + 
  ylab(NULL) +
  ggtitle("Obstacles to moving")

move_obstacles

由reprex package (v2.0.0) 于 2021-07-08 创建

如您所见,即使我包含了重新排序 ggplot(aes(reorder(obstacle,n),n)) 的代码,条形也不是按数量级排列的。

我该如何解决这个问题?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    默认情况下,reorder 在多个观测值的情况下使用平均值。如果您想按数量订购,请改用FUN=sum:

    library(tidyverse)
    move_obstacles = tibble::tribble(
      ~move_approach,                           ~obstacle, ~n,
      "Relocate", "Distance from business activities", 1L,
      "Relocate",                      "No customers", 1L,
      "Relocate",                       "No services", 1L,
      "Upgrade Existing",                      "Cost of move", 4L,
      "Upgrade Existing", "Distance from business activities", 6L,
      "Upgrade Existing",                       "Higher rent", 1L,
      "Upgrade Existing",                      "Higher taxes", 2L,
      "Upgrade Existing",                      "No customers", 6L,
      "Upgrade Existing",                       "No services", 3L
    ) %>%
      ggplot(aes(reorder(obstacle, n, FUN = sum),n)) +
      geom_col() +
      theme_bw() + 
      coord_flip() +
      xlab(NULL) + 
      ylab(NULL) +
      ggtitle("Obstacles to moving")
    
    move_obstacles
    

    【讨论】:

    • 谢谢你。我可以看到这行得通,我不确定我是否理解“默认情况下重新排序取平均值”的意思是什么意思?
    • 嗨图马尼。 n 的平均值。您有多个 obs,例如“没有客户”。因为只能按一个值重新排序 reorder 默认情况下采用所有 n 值的平均值(按类别)。相比之下,geom_col 堆叠 obs,即它计算 n 的总和。这就是为什么我们必须告诉reorder 也使用总和。
    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 2019-03-22
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多