R语言 ggplot中分类变量的手动排序被更改

6kkfgxo0  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(123)

我手动将我的类别重新排序为:

bite_anatomy_other_variables <- bite_anatomy_other_variables %>% 
   mutate(species = fct_relevel(species,
                                "Pet dog" , "Unowned dog" , "Dog (unknown status)",
                                "Pet cat" , "Unowned cat" , "Cat (unknown status)",
                                "Rat/rodent" , "Monkey" , "Livestock (cattle/goat/sheep/pig/horse)"))

然后当我用下面的代码做一个图时,顺序就变了

bite_anatomy_other_variables %>%
  filter(!(species %in% c("Monkey", "Livestock (cattle/goat/sheep/pig/horse)"))) %>%
  add_count(species) %>%
  mutate(species = factor(species, levels = species_order)) %>%
  mutate(species = paste0(species, "\n", "(n = ", n, ")")) %>% # THIS CODE CREATES ISSUES
  ggplot(mapping = aes(y = species, fill = body_part_collapsed)) +
  geom_bar(colour = "black", position = "fill") +
  scale_x_continuous(labels = c("0", "25%", "50%", "75%", "100%")) +
  labs(x = "Proportion of responses", y = "Animal species") +
  ggtitle("Body part exposed")

当我没有使用“mutate(species = paste 0(species,“\n”,“(n =“,n,“)”)%>%”时,手动顺序保持预期的方式。
现在,当我使用上面的代码时,顺序发生了变化,我似乎无法返回它。你能帮我按我想要的类别顺序显示图表吗?
Undesired order
Desired order but with the "(n = xxx)" in the y-axis

vmdwslir

vmdwslir1#

一个labeler(正如我在评论中所建议的)实际上不会那么容易工作,因为它需要来自另一列的输入。相反,我使用注解创建了一个新因子,并使用reorder来匹配手动排序的版本:

bite_anatomy_other_variables %>%
  filter(!(species %in% c("Monkey", "Livestock (cattle/goat/sheep/pig/horse)"))) %>%
  add_count(species) %>%
  mutate(y_species = 
    reorder(
      factor(paste0(species, "\n", "(n = ", n, ")")),
      as.numeric(species)
  )) %>% 
  ggplot(mapping = aes(y = y_species, fill = body_part_collapsed)) +
  geom_bar(colour = "black", position = "fill") +
  scale_x_continuous(labels = c("0", "25%", "50%", "75%", "100%")) +
  labs(x = "Proportion of responses", y = "Animal species") +
  ggtitle("Body part exposed")

相关问题