首页 文章

重新排序因子不适用于分组数据

提问于
浏览
0

我有这个数据框,我称之为 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))

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

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

2 回答

  • 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 - 如果没有额外的包依赖,它会做同样的事情 . )

  • 1

    这个怎么样?

    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) 来改变顺序 .

相关问题