ggplot2: How to use same colors in different plots for same factor
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)
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)