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

时间:2018-12-10 01:34:59

标签: r ggplot2 dplyr

我有一个称为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))

正如标题所示,我想按termbeta列重新排序,然后绘制一个条形图。我希望看到有条形的条形图,但事实并非如此。这是我使用的代码以及生成的图形:

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

enter image description here

2 个答案:

答案 0 :(得分:0)

怎么样?

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)更改了订单。

答案 1 :(得分:0)

您的问题是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")

enter image description here

(顺便说一句,forcats有一些非常不错的功能,但是如果您唯一需要的功能是fct_reorder,那么您不妨使用base::reorder-它做同样的事情而无需额外的软件包依赖性。)