ggplot2: Fix colors to factor levels

前端 未结 4 2002
借酒劲吻你
借酒劲吻你 2020-12-10 12:50

I\'m working on a larger project for which I am creating several plots in ggplot2. The plots are concerned with plotting several different outcomes across several different

4条回答
  •  借酒劲吻你
    2020-12-10 13:05

    You could define your own custom scale, if you like. If you look at the source for scale_fill_manual,

    scale_fill_manual
    #> function (..., values) 
    #> {
    #>     manual_scale("fill", values, ...)
    #> }
    #> 
    

    it's actually quite simple:

    library(ggplot2)
    
    scale_fill_chris <- function(...){
        ggplot2:::manual_scale(
            'fill', 
            values = setNames(c('green', 'blue', 'red', 'orange'), LETTERS[1:4]), 
            ...
        )
    }
    
    df1 <- data.frame(Value = c(40, 20, 10, 60), 
                      Type = c("A", "B", "C", "D"))
    
    ggplot(df1, aes(x = Type, y = Value, fill = Type)) + 
        geom_col() + 
        scale_fill_chris()
    

    df2 <- data.frame(Value = c(40, 20, 60), 
                      Type = c("A", "B", "D"))
    
    ggplot(df2, aes(x = Type, y = Value, fill = Type)) + 
        geom_col() + 
        scale_fill_chris()
    

    df3 <- data.frame(Value = c(40, 20, 10, 60), 
                      Type = c("A", "B", "C", "D"))
    df3$Type <- factor(df3$Type, levels = c("D", "C", "B", "A"), ordered = TRUE)
    
    ggplot(df3, aes(x = Type, y = Value, fill = Type)) + 
        geom_col() + 
        scale_fill_chris()
    

提交回复
热议问题