JerryWho
JerryWho

Reputation: 3105

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

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)
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))

When plotting them using c as color-indicator I get the same five colors.

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

enter image description here

But I want that same values of c get the same color.

Upvotes: 22

Views: 15712

Answers (3)

JerryWho
JerryWho

Reputation: 3105

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

Upvotes: 11

agstudy
agstudy

Reputation: 121568

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

Upvotes: 20

Paul Hiemstra
Paul Hiemstra

Reputation: 60924

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.

Upvotes: 8

Related Questions