堆叠条形图:如何使用forcats软件包安排组

时间:2019-02-21 16:28:23

标签: r ggplot2 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))

enter image description here

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

要定义顺序,请将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))

enter image description here