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)

enter image description here

Leave a Comment