0

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

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

4

2 回答 2

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

于 2019-02-21T19:45:52.107 回答
0

要定义顺序,cyl请使用 desired 转换为因子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))

在此处输入图像描述

于 2019-02-21T16:32:26.333 回答