堆叠条形图:如何使用 forcats 包排列组

Stacked bar chart: How to arrange the groups with forcats package

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

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...

要定义顺序,请将 cyl 转换为具有所需 levels 的因数。

df1 = mtcars
df1$cyl = factor(df1$cyl, levels = c(6, 4, 8))
df1 %>% 
    group_by(cyl) %>% 
    summarise(n=n()) %>% 
    ungroup() %>% 
    mutate(cars = "cars") %>% 
    ggplot(aes(x = as.factor(cars), y = n, fill=as.factor(cyl))) +
    #scale_fill_manual(values=c("green", "red", "blue")) +
    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))

这是您要找的吗?要更改填充颜色,请使用 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))