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

前端 未结 3 832
春和景丽
春和景丽 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

提交回复
热议问题