首页 > 解决方案 > 堆积条形图:如何使用 forcats 包排列组

问题描述

我正在制作一些漂亮的情节,我可以在需要时复制粘贴(这就是我包含这么多选项的原因)。所以我有这个情节:

library(tidyverse)
    mtcars %>% 
      group_by(cyl) %>% 
      summarise(n=n()) %>% 
      ungroup() %>% 
      mutate(cars = "cars") %>% 
      ggplot(aes(x = as.factor(cars), y = n, fill=as.factor(cyl))) +
      geom_bar(stat="identity", width = .3) +
      geom_text(aes(label = paste0(round(n, digits = 0), "stk.")),
                position = position_stack(vjust = 0.5)) +
      labs(title = "Number of cars with cylinders in the data set", 
           subtitle= "If needed",
           caption= "Fodnote",
           x= "", y="Antal",
           fill="# of cylinders") +
      theme(#legend.position="none",
            plot.caption = element_text(hjust = 0))

在此处输入图像描述

我如何重新排序堆栈,例如蓝色在底部,然后是红色堆栈和绿色堆栈在顶部。谢谢。我认为解决方案涉及forcats...

标签: rggplot2forcats

解决方案


这是你要找的吗?要更改填充颜色,请使用scale_fill_manual()scale_fill_brewer()

library(tidyverse)
library(forcats)

mtcars %>% 
  group_by(cyl) %>% 
  summarise(n=n()) %>% 
  ungroup() %>% 
  mutate(cars = "cars",
         cars = factor(cars),
         cyl  = factor(cyl)) %>% 

  # use fct_reorder here
  mutate(cyl = fct_reorder(cyl, n)) %>% 

  ggplot(aes(x = cars, y = n, fill = cyl)) +
  geom_col(width = .3) +
  geom_text(aes(label = paste0(round(n, digits = 0), "stk.")),
            position = position_stack(vjust = 0.5)) +
  labs(title = "Number of cars with cylinders in the data set", 
       subtitle = "If needed",
       caption = "Footnote",
       x = "", y = "Antal",
       fill = "# of cylinders") +
  theme(#legend.position="none",
    plot.caption = element_text(hjust = 0))


推荐阅读