在ggplot2中为colorbar(图例)指定相同的限制

gen*_*ser 1 plot r heatmap ggplot2

我想要多个图表共享相同的颜色比例.一个图中的给定值应与第二个图中的颜色相同.我该如何执行此操作ggplot2

以下是两个不共享色阶的图表示例,但应该:

x <- matrix(1:16, 4)
y <- matrix(1:16-5, 4)
library(reshape)
ggplot(data = melt(x)) + geom_tile(aes(x=X1,y=X2,fill = value))
ggplot(data = melt(y)) + geom_tile(aes(x=X1,y=X2,fill = value))
Run Code Online (Sandbox Code Playgroud)

这两个图看起来一样,但它们应该看起来不同!

M--*_*M-- 8

您需要将比例尺的限制设置为具有某些颜色,并将平均值(中间的值)定义为两个图的相同值.

rng = range(c((x), (y))) #a range to have the same min and max for both plots



ggplot(data = melt(x)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
  scale_fill_gradient2(low="blue", mid="cyan", high="purple", #colors in the scale
                 midpoint=mean(rng),    #same midpoint for plots (mean of the range)
                 breaks=seq(-100,100,4), #breaks in the scale bar
                 limits=c(floor(rng[1]), ceiling(rng[2]))) #same limits for plots

ggplot(data = melt(y)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
  scale_fill_gradient2(low="blue", mid="cyan", high="purple", 
                 midpoint=mean(rng),    
                 breaks=seq(-100,100,4),
                 limits=c(floor(rng[1]), ceiling(rng[2])))
Run Code Online (Sandbox Code Playgroud)

这是输出: