【问题标题】:Reorder factor not working on grouped data重新排序因子不适用于分组数据
【发布时间】:2019-05-10 22:14:32
【问题描述】:

我有这个数据框,我称之为top_mesh_terms

structure(list(topic = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), term = c("Diabetes Mellitus", 
"Depression", "Syndrome", "Diabetes Mellitus, Type 2", "Lung Diseases", 
"Colorectal Neoplasms", "Osteoarthritis", "Sclerosis", "Lymphoma", 
"Lung Diseases, Obstructive", "Diabetes Mellitus", "Disease", 
"Hypertension", "Syndrome", "Carcinoma", "Infection", "Coronary Disease", 
"Lung Neoplasms", "Obesity", "Infarction"), beta = c(0.0196989252285569, 
0.018472562347772, 0.0175512616261399, 0.0146680780420432, 0.0133507951269683, 
0.01224603797061, 0.0116799262133244, 0.0107893497000735, 0.00926496950657875, 
0.00891926541108836, 0.0324598963852768, 0.0198135918084849, 
0.0162689075944415, 0.0157166860189554, 0.014855885836076, 0.0127365678034364, 
0.0109544570325732, 0.00964124158432716, 0.00956596829604797, 
0.00880281359338067)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -20L))

正如标题所示,我想将term 列按beta 重新排序,然后绘制条形图。我希望看到带有有序条形的条形图,但事实并非如此。这是我使用的代码和结果图:

top_mesh_terms %>% 
  group_by(topic) %>% 
  mutate(term = fct_reorder(term, beta)) %>%
  ungroup() %>% 
  ggplot(aes(term, beta)) +
  geom_bar(stat = "identity") +
  facet_wrap(~ topic, scales = "free") +
  coord_flip() +
  scale_y_continuous(labels = scales::percent_format()) +
  labs(x = "MeSH Term",
       y = "Beta")

【问题讨论】:

标签: r ggplot2 dplyr


【解决方案1】:

您的问题是group_by。一个因素的水平有一个单一的顺序,它不能因组而异。如果我们摆脱您的 group_byungroup 命令,一切正常:

    top_mesh_terms %>% 
      mutate(term = reorder(term, beta)) %>%
      ggplot(aes(term, beta)) +
      geom_bar(stat = "identity") +
      facet_wrap(~ topic, scales = "free") +
      coord_flip() +
      scale_y_continuous(labels = scales::percent_format()) +
      labs(x = "MeSH Term",
           y = "Beta")

(顺便说一句,forcats 有一些非常好的功能,但如果您唯一需要的是fct_reorder,您不妨使用base::reorder - 它在没有额外包依赖的情况下做同样的事情。)

【讨论】:

    【解决方案2】:

    这个怎么样?

    top_mesh_terms %>% 
      group_by(topic) %>% 
      mutate(term = fct_reorder(term, beta)) %>%
      ungroup() %>% 
      ggplot(aes(reorder(term, beta), beta)) +
      geom_bar(stat = "identity") +
      facet_wrap(~ topic, scales = "free") +
      coord_flip() +
      scale_y_continuous(labels = scales::percent_format()) +
      labs(x = "MeSH Term",
           y = "Beta")
    

    我使用ggplot(aes(reorder(term, beta) 更改订单。

    【讨论】:

    • 对不起,当我打算将其添加到我的答案时,我错误地在您的答案中添加了脚注。刚刚回滚了更改。
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多