【问题标题】:How to change the order of aesthetic layers in ggplot?如何更改ggplot中美学层的顺序?
【发布时间】:2020-02-04 17:08:17
【问题描述】:

如何更改美学层的顺序? 这是和示例

dat <- tibble (acc = rep(c(0,1), 200),
               rt = rnorm(400, 0.5, 0.1))

dat %>% ggplot(aes(x = rt, fill = factor(acc))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)

此代码绘制此图像。这里,绿色 (1) 层位于红色 (0) 层之上。如何将红色 (0) 图层放在绿色 (1) 之上?

我试过了

dat %>% ggplot(aes(x = rt, fill = factor(acc, levels = c(1,0)))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)

但这会导致切换颜色位置!

【问题讨论】:

  • 你试过改变关卡顺序吗?例如factor(acc, levels = c(1,0))?
  • 是的,但这会切换颜色和位置。

标签: r ggplot2 layer


【解决方案1】:

您可以重新排序factor 的级别并添加颜色调整:

dat %>% ggplot(aes(x = rt, 
                   fill = factor(acc, levels = c(1,0)))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)+
scale_fill_manual(values = c("1" = "#00BFC4", "0" = "#F8766D"))

【讨论】:

  • 能否请您更准确地提供颜色调整代码?谢谢!
【解决方案2】:

好的,我只是想添加一个关于啤酒调色板的答案,这更简单。

所以,原始数据:

dat <- tibble (acc = rep(c(0,1), 200),
               rt = rnorm(400, 0.5, 0.1))

dat %>% ggplot(aes(x = rt, fill = factor(acc))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)+
  scale_fill_brewer(palette = "Set1")

切换颜色

dat %>% ggplot(aes(x = rt, fill = factor(acc))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)+
  scale_fill_brewer(palette = "Set1", direction = -1)

开关位置

dat %>% ggplot(aes(x = rt, fill = factor(acc, levels = c(1,0)))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)+
  scale_fill_brewer(palette = "Set1", direction = -1)

切换位置和颜色

dat %>% ggplot(aes(x = rt, fill = factor(acc, levels = c(1,0)))) + 
  geom_density(aes(y= ..count..*0.03), alpha = 0.6)+
  scale_fill_brewer(palette = "Set1")

【讨论】:

    【解决方案3】:

    有趣。通常很简单,只需将direction= -1 添加到您的scale_fill 函数中即可。但这目前不起作用。

    如果您想保留 ggplot2 默认调色板(我认为这可能不是最好的主意),那么以下方法有效 (inspired by this answer)

    使用最新的 scale 包 v.1.1.0 ,direction = -1 参数似乎破坏了 scale::hue_pal() 函数(see this SO threadthis github bug report),所以这里将是一个明确调用 @987654333 的解决方法@ 以创建您的调色板。

    library(tidyverse)
    
    dat <- tibble(
      acc = rep(c(0, 1), 200),
      rt = rnorm(400, 0.5, 0.1)
    )
    
    dat %>% ggplot(aes(x = rt, fill = factor(acc))) +
      geom_density(aes(y = ..count.. * 0.03), alpha = 0.6) +
      scale_fill_manual(values = rev(scales::hue_pal()(length(unique(dat$acc)))))
    

    我通常建议不要使用默认调色板以外的其他颜色。 colorbrewer 是一个不错的选择 - colorbrewer2.org 非常好,它可以帮助您找到好的调色板。

    使用“Dark2”的示例:

    
    dat %>% ggplot(aes(x = rt, fill = factor(acc))) +
      geom_density(aes(y = ..count.. * 0.03), alpha = 0.6) +
    scale_fill_brewer(type = 'qual', palette = 'Dark2')
    

    reprex package (v0.3.0) 于 2020 年 2 月 4 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      相关资源
      最近更新 更多