我希望多个图表共享相同的色阶。一个图中的给定值应与第二个图中的颜色相同。如何使用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))
这两个情节看起来一样,但看起来应该不一样了!
答案 0 :(得分:7)
您需要将比例尺的限制设置为具有某些颜色,并将平均值(中间的值)定义为两个图的相同值。
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])))
这是输出: