I am trying to display multiple layers in ggplot2
, but I would like to use different scale_fill_
color schemes for each layer. I cannot do this, since calling something like scale_fill_gradientn
twice just overwrites the first call with the second.
library( ggplot2 ) library( reshape2 ) library( RColorBrewer ) set.seed( 123 )
I will first build the tile
grid (note that I set the colors using scale_fill_gradientn
):
foo <- matrix( data = rnorm( 100 ), ncol = 10 ) foo <- melt( foo ) plot <- ggplot() + geom_tile( data = foo, mapping = aes( x = Var1, y = Var2, fill = value ) ) + scale_fill_gradientn( colours = rev( brewer.pal( 7, "BrBG" ) ) ) plot
Now I would like to add another plot on top of this, but with a unique color scheme. I can create a great storyline simply:
bar <- data.frame( x = rnorm( 100, 4, 1 ), y = rnorm( 100, 6, 1.5 ) ) ggplot() + stat_density_2d( data = bar, mapping = aes( x = x, y = y, fill = ..level.. ), geom = "polygon" ) + scale_fill_gradientn( colours = rev( brewer.pal( 7, "Spectral" ) ) ) + xlim( 0, 10 ) + ylim( 0, 10 )
What I would like to do is to speak the second plot on top of the first, but keep the color schemes that you see above. If I try to just add a second layer on top of the first, I overwrite the original scale_fill_gradientn
and force the two layers to share the same color scheme (which in this case also “compresses” the second layer, completely falling within the same color:
plot <- plot + stat_density_2d( data = bar, mapping = aes( x = x, y = y, fill = ..level.. ), geom = "polygon" ) + scale_fill_gradientn( colours = rev( brewer.pal( 7, "Spectral" ) ) ) + xlim( 0, 10 ) + ylim( 0, 10 ) plot
Is there a way to specify separate color schemes for each layer? I noticed that, for example, stat_density_2d
understands the aesthetics of colour
, but I tried to specify it to no avail (it only adds color as a label in the legend and returns the default color scheme):
ggplot() + stat_density_2d( data = bar, mapping = aes( x = x, y = y, fill = ..level.., colour = "red" ), geom = "polygon" ) + xlim( 0, 10 ) + ylim( 0, 10 )
I feel that there should be a different way to set the color scheme to “per layer”, but I was clearly looking for the wrong places.