好的,从上一个示例中获取数据集:
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))
因此,如果我们使用 grid.arrange 将两个图绘制在一起,您应该会得到:
grid.arrange(arrangeGrob(p1,
p2,
nrow = 1))
Graphs without equivalent color scale
因此,我们希望两个图表的范围相同,并且只绘制其中一个结肠囊。您需要做的是首先定义色标的范围。在这个例子中,让我们从:
summary(mtcars$carb)
>
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.000 2.000 2.000 2.812 4.000 8.000
所以我们知道色阶应该是从 1 到 8。我们将这个范围定义为 col.range,然后我们用它来指定每个图形中的范围:
#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))
这将为您提供以下图表。现在,两个图表之间的颜色是可比较的。
Graphs with same color scale
但是重复的结肠秤是多余的,所以我们只想使用一个。
所以为了得到漂亮的最终图,我们可以使用我们之前定义的相同的 p1 和 p2 图,我们只是在 grid.arrange 函数上指定为:
#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
这样你就完成了,得到下图:
Graphs with just one color scale
希望有用!!!!!!
请评价!!!!