【问题标题】:Reorder Function in R Issues [duplicate]R问题中的重新排序功能[重复]
【发布时间】:2022-02-09 07:52:21
【问题描述】:

我正在尝试添加重新排序以使数据集从最大到最小排列但有问题。

ggplot(Manager_Graph_Data, aes(x = reorder(Manager_Graph_Data$`Completion Rate`), y = Manager_Graph_Data$Manager)) +
  geom_bar(stat="identity", 
           position="identity", 
           fill="#0077b5")

structure(list(Manager = c("Bob Beno", "Dylan Tracy", "Ignacia Lemley", 
"Jaimee Cogdill", "Jeneva Engman", "Julianne Holdren", "Lakia Farrington", 
"Lester Braden", "Soon Mooneyham"), Complete = c(5, 5, 1, 4, 
0, 0, 3, 2, 5), Incomplete = c(6, 6, 7, 2, 3, 4, 5, 2, 3), Total = c(11, 
11, 8, 6, 3, 4, 8, 4, 8), `Completion Rate` = c(0.454545454545455, 
0.454545454545455, 0.125, 0.666666666666667, 0, 0, 0.375, 0.5, 
0.625)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-9L))

任何帮助将不胜感激

【问题讨论】:

  • Don't use $ inside aes。您还调用了reorder,它不会对分类列(经理)做任何事情——您只是在要排序的列上调用它

标签: r ggplot2


【解决方案1】:

您似乎正在尝试按完成率排序。当您有条形图或柱形图时,ggplot 将按因子(或字符)字段排序。因此,要更改顺序,请设置因子水平。有多种方法可以做到这一点。这是一种方法:

library(tidyverse)

# order by rate decreasing 
MgrRate <- Manager_Graph_Data %>% 
  arrange(`Completion Rate`, decreasing = T) %>% 
  mutate(Manager = ordered(Manager, levels = .$Manager))

ggplot(MgrRate, 
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_bar(stat="identity", 
           position="identity", 
           fill="#0077b5")

如果您不知道,如果您想设置 x 和 y,请尝试使用 geom_col() 来简化操作。

# alternatively (creating the same plot)
ggplot(MgrRate, 
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_col(fill="#0077b5")

如果您真的想由经理订购,这里有一个示例说明如何执行此操作。 (这是经理的名字。)

# order by manager's first name
Mgr <- Manager_Graph_Data %>% 
  arrange(desc(Manager)) %>% 
  mutate(Manager = ordered(Manager, levels = .$Manager))

ggplot(Mgr, 
       aes(x = `Completion Rate`,
           y = Manager)) +
  geom_col(fill="#0077b5")

请注意,当您翻转轴时(但 y 上的因子,而不是 x),您必须颠倒顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多