How to change the order of aesthetic layers in ggplot?

后端 未结 3 415
天涯浪人
天涯浪人 2021-01-15 19:04

How can I change the order of aestetics layers? Here\'s and example

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

dat          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-15 19:08

    Interesting. Usually it's very simple, just adding direction= -1 to your scale_fill function. But this does not currently work.

    If you want to keep the ggplot2 default palette (which I think may not be the best idea), then the following approach works (inspired by this answer)

    With the latest scale package v.1.1.0 , the direction = -1 argument seems to break the scale::hue_pal() function (see this SO thread or this github bug report), so here would be a workaround with explicitely calling scales::hue_pal in order to create your palette.

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

    I generally recommend rather to use other colors than the default palette. A good choice is colorbrewer - very good is colorbrewer2.org which helps you finding good palettes.

    An example using "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')
    

    Created on 2020-02-04 by the reprex package (v0.3.0)

提交回复
热议问题