如何更改ggplot中美学层的顺序?

How to change the order of aesthetic layers in ggplot?

如何更改美学层的顺序? 这是一个例子

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 的级别并添加颜色调整:

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

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

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

对于最新的 scale 软件包 v.1.1.0 ,direction = -1 参数似乎破坏了 scale::hue_pal() 函数( or this github bug report),所以这里是明确调用 scales::hue_pal 以创建调色板的解决方法。

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-02-04 创建

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

所以,原始数据:

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