【问题标题】:ggplot geom_boxplot color and group variablesggplot geom_boxplot 颜色和组变量
【发布时间】:2019-03-27 18:26:10
【问题描述】:

我正在尝试在 ggplot 中制作一个简单的箱线图。我不确定如何获得分组变量和颜色/填充变量。我试图收集,但这似乎不起作用。有什么想法吗?

library(tidyverse)
# Does not work
mtcars %>% 
  as_tibble() %>% 
  ggplot(aes(factor(gear), 
             mpg, 
             group = vs)) +
  geom_boxplot(aes(fill = as.factor(gear)))


# Does not work either
mtcars %>% 
  as_tibble() %>% 
  select(gear, mpg, vs) %>% 
  gather(key, value, -vs) %>% 
  ggplot(aes(key, 
             value)) +
  geom_boxplot(aes(color = vs))

【问题讨论】:

    标签: r ggplot2 colors


    【解决方案1】:

    我不确定这是您想要的输出(gear 作为 x 轴和 fill),但这是一个工作示例:

    mtcars %>%
      ggplot(
        aes(
          x = factor(gear),
          y = mpg,
          color = factor(vs),
          fill = factor(gear)
        )
      ) + geom_boxplot()
    

    我发现,在学习ggplot2 时,明确地声明你的审美映射会很有帮助。

    【讨论】:

      【解决方案2】:

      或者:

      mtcars %>% 
        as_tibble() %>% 
        group_by(vs) %>% 
        ggplot(aes(factor(gear), 
                   mpg, 
                   fill=as.factor(gear))) +
        geom_boxplot()
      

      【讨论】:

        猜你喜欢
        • 2022-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-10
        • 2020-11-12
        • 2021-06-26
        • 2020-11-27
        • 2023-03-16
        相关资源
        最近更新 更多