Ok so taking the data set from the previous example:
library(ggplot2)
library(RColorBrewer)
library(gridExtra)
library(gtablegridExtra)
#Using the mtcars data set
#Generate plot 1
p1=ggplot(subset(mtcars, am==0), aes(x=wt, y=mpg, colour=carb)) +
geom_point(size=2)+
labs(title="Graph 1")+
scale_color_gradientn(colours=rainbow(5))
#Generate plot 2
p2=ggplot(subset(mtcars, am==1), aes(x=wt, y=mpg, colour=carb)) +
geom_point(size=2)+
labs(title="Graph 2")+
scale_color_gradientn(colours=rainbow(5))
So if we plot both graphs together using grid.arrange you should get this:
grid.arrange(arrangeGrob(p1,
p2,
nrow = 1))
Graphs without equivalent color scale
So we want to get the same range for both graphs and plot only one of this colos sacles. What you need to do is first define the range of the of your color scale. in this example lets do it from:
summary(mtcars$carb)
>
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.000 2.000 2.000 2.812 4.000 8.000
So we know that the color scale should be from 1 to 8. We define this range as col.range and we then use it to specify the range in each graph:
#Define color range
col.range=c(1,8)
#Generate plot 1
p1=ggplot(subset(mtcars, am==0), aes(x=wt, y=mpg, colour=carb)) +
geom_point(size=2)+
labs(title="Graph 1")+
scale_color_gradientn(colours=rainbow(5),limits=col.range) #look here
#Generate plot 2
p2=ggplot(subset(mtcars, am==1), aes(x=wt, y=mpg, colour=carb)) +
geom_point(size=2)+
labs(title="Graph 2")+
scale_color_gradientn(colours=rainbow(5),limits=col.range) #look here
#Plot both graphs together
grid.arrange(arrangeGrob(p1,
p2,
nrow = 1))
This will get you the following graph. Now the color is comparable between both graphs.
Graphs with same color scale
However the repeated colos scale is redundant, so we want to use only one.
So to get that nice final graph we can use the same p1 and p2 graphs that we defined previously, we just especified on the grid.arrange function as:
#Create al element that will represent your color scale:
color.legend=gtable_filter(ggplotGrob(p1),"guide-box")
#We hide de color scale on each individual graph
#Then we insert the color scale and we adjust the ratio of it with the graphs
#For this we define the theme() as follows:
grid.arrange(arrangeGrob(p1+theme(legend.position="none"),
p2+theme(legend.position="none"),
nrow = 1), #Here we have just remove the color scale
color.scale, #We inserted the color scale.
nrow=1, #We put the color scale to the right of the graph
widths=c(20,1) #With this we make the color scale much narrower
So with this you are done, getting the following graph:
Graphs with just one color scale
Hope is is usefull!!!!!!
Please rate!!!!! <3