ggplot2: How to use same colors in different plots for same factor

前端 未结 3 812
春和景丽
春和景丽 2020-11-30 09:45

How can I pin the same color to a value in diffent plots?

Say I have two data.frames df1 and df2:

library(ggplot2)
library(gridExtra)

set.seed(1)
d         


        
相关标签:
3条回答
  • 2020-11-30 10:29

    I now wrote a function which generates another function which computes the colors. I'm not sure if it's a good way. Comments appreciated.

    library(ggplot2)
    library(gridExtra)
    library(RColorBrewer)
    
    makeColors <- function(){
      maxColors <- 10
      usedColors <- c()
      possibleColors <- colorRampPalette( brewer.pal( 9 , "Set1" ) )(maxColors)
    
      function(values){
        newKeys <- setdiff(values, names(usedColors))
        newColors <- possibleColors[1:length(newKeys)]
        usedColors.new <-  c(usedColors, newColors)
        names(usedColors.new) <- c(names(usedColors), newKeys)
        usedColors <<- usedColors.new
    
        possibleColors <<- possibleColors[length(newKeys)+1:maxColors]
        usedColors
      }
    } 
    
    mkColor <- makeColors()
    
    
    set.seed(1)
    df1 <- data.frame(c=c('a', 'b', 'c', 'd', 'e'), x=1:5,  y=runif(5))
    df2 <- data.frame(c=c('a', 'c', 'e', 'g', 'h'), x=1:5,  y=runif(5))
    
    g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") + scale_fill_manual(values = mkColor(df1$c))
    g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + geom_bar(stat="identity") + scale_fill_manual(values = mkColor(df2$c))
    grid.arrange(g1, g2, ncol=2)
    

    enter image description here

    0 讨论(0)
  • 2020-11-30 10:34

    You can set your own fill scale using scale_fill_manual. I create a named vector with colors and different values of "c".

    dd <- union(df1$c,df2$c)
    dd.col <- rainbow(length(dd))
    names(dd.col)  <- dd
    

    Then :

    g1 <- ggplot(df1, aes(x=x, y=y, fill=c)) + 
      geom_bar(stat="identity") +
      scale_fill_manual("Legend", values = dd.col)
    g2 <- ggplot(df2, aes(x=x, y=y, fill=c)) + 
      geom_bar(stat="identity") +
      scale_fill_manual("Legend", values = dd.col)
    grid.arrange(g1, g2, ncol=2)
    

    enter image description here

    0 讨论(0)
  • 2020-11-30 10:34

    To make this kind of composite plots, ggplot2 has facets:

    df1$id = 'A'
    df2$id = 'B'
    df_all = rbind(df1, df2)
    ggplot(df_all, aes(x=x, y=y, fill=c)) + 
        geom_bar(stat="identity") + 
        facet_wrap(~id)
    

    enter image description here

    When using facets, ggplot2 treats both plots as one whole, keeping the color-value mapping the same.

    0 讨论(0)
提交回复
热议问题