Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple ggplot2 scale_fill_gradientn with same scale?

Tags:

r

ggplot2

library(ggplot2)
library(cumplyr)
library(scales)
library(RColorBrewer)


myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))

x   = 1:5
y   = 1:5
pts = cartesian_product(c('x','y'))
d1 = cbind(pts, runif(nrow(pts),min=0,max=1), 1)
d2 = cbind(pts, runif(nrow(pts),min=0,max=4), 2)
colnames(d1) = colnames(d2) = c("x","y","val","k")
d  = rbind(d1,d2)

p1 <- ggplot(d1)
p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))
p1 <- p1 + scale_fill_gradientn(colours = myPalette(4))
p1

p2 <- ggplot(d2, aes(x = x, y = y, fill = val))
p2 <- p2 + geom_tile(aes(x = x, y = y, fill = val)) 
p2 <- p2 + scale_fill_gradientn(colours = myPalette(4))
p2

And this leads to the two plots below. My question is, using this same type of color scheme, how do I get both plots to use the same scale for value? E.g. p1 should be much more uniform than p2.

p1: p1

p2: enter image description here

like image 831
stevejb Avatar asked Mar 06 '14 20:03

stevejb


2 Answers

Use limit in scale_gradientn:

p1 <- ggplot(as.data.frame(d1))
p1 <- p1 + geom_tile(aes(x = x, y = y, fill = val))

p2 <- ggplot(as.data.frame(d2), aes(x = x, y = y, fill = val))
p2 <- p2 + geom_tile(aes(x = x, y = y, fill = val)) 
library(gridExtra)

p1 <- p1 + scale_fill_gradientn(colours = myPalette(4), limits=c(0,4))
p2 <- p2 + scale_fill_gradientn(colours = myPalette(4), limits=c(0,4))
grid.arrange(p1, p2)

enter image description here

The grid.arrange stuff is just to avoid me having to copy/paste two pictures.

like image 127
BrodieG Avatar answered Oct 09 '22 16:10

BrodieG


In scale_fill_gradientn set the limits to be the same, so for example:

scale_fill_gradientn(colours = myPalette(4),limits=c(0,4))

And this is p1 and p2:

p1

p2

like image 27
Christie Haskell Marsh Avatar answered Oct 09 '22 16:10

Christie Haskell Marsh