Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using two scale colour gradients ggplot2

Tags:

If any, I think there must be a very easy solution for this. I have two large dataframes that basically look like these:

> data1[1,]       chromosome start    end      test ref position log2      p.value  13600 Y          10199251 10200750 533  616 10200000 0.2181711 0.00175895    ...  > data2[1,]       chromosome start    end      test ref position log2       p.value  4080  Y          10197501 10202500 403  367 10200000 0.04113596 0.3149926    ... 

I'm using this code to plot the two dataframes into the same graph:

p <- ggplot() + geom_point(data=subset(data1, p.value >= glim[1]), map=aes(x=position, y=log2, colour=p.value)) + geom_point(data=subset(data2, p.value >= glim[1]), map=aes(x=position, y=log2, colour=p.value)) 

When I was plotting single dataframes, I was using a red-white color gradient for the values in "p.value" column. Using this line:

p <- p + scale_colour_gradient(limits=glim, trans='log10', low="red",  high="white")  

The central issue is: Now with two dataframes, how can I set one color gradient for data1 and another for data2? I read in a previous post that it is not possible to use two different colour scales(ej. "low=" for the first, and "high=" for the second), but in this case is exactly the same kind of colour scale (If I'm not mixing up terminology). The syntax obviously is not correct but I'd like to do something like this:

p <- p + scale_colour_gradient(limits=glim, trans='log10', low="red",  high="white")   p <- p + scale_colour_gradient(limits=glim, trans='log10', low="blue",  high="white")  
like image 465
JRodrigoF Avatar asked Aug 21 '13 00:08

JRodrigoF


2 Answers

First, note that the reason ggplot doesn't encourage this is because the plots tend to be difficult to interpret.

You can get your two color gradient scales, by resorting to a bit of a cheat. In geom_point certain shapes (21 to 25) can have both a fill and a color. You can exploit that to create one layer with a "fill" scale and another with a "color" scale.

# dummy up data dat1<-data.frame(log2=rnorm(50), p.value= runif(50)) dat2<-data.frame(log2=rnorm(50), p.value= runif(50))  # geom_point with two scales p <- ggplot() +        geom_point(data=dat1, aes(x=p.value, y=log2, color=p.value), shape=21, size=3) +        scale_color_gradient(low="red", high="gray50") +        geom_point(data= dat2, aes(x=p.value, y=log2, shape=shp, fill=p.value), shape=21, size=2) +        scale_fill_gradient(low="gray90", high="blue") p 

enter image description here

like image 141
Ram Narasimhan Avatar answered Oct 13 '22 13:10

Ram Narasimhan


I know this is a long time after, but have a look at https://github.com/eliocamp/ggnewscale.

You can use the function new_colour_scale() to start a new colour scale that applies to everything after it.

like image 26
masher Avatar answered Oct 13 '22 13:10

masher