在ggplot2中为色条(图例)指定相同的限制 [英] Specifying same limits for colorbar (legend) in ggplot2

查看:194
本文介绍了在ggplot2中为色条(图例)指定相同的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望多个图共享相同的色标.一个绘图中的给定值应与第二个绘图中的颜色相同.如何使用ggplot2强制执行此操作?

I want multiple plots to share the same color-scale. A given value in one plot should have the same color as in the second plot. How do I enforce this with ggplot2?

这是两个不共享色标的图的示例,但是应该:

Here is an example of two plots that do not share color-scales, but should:

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))

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

These two plots look the same, but they should look different!

推荐答案

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

You need to set the limits of your scale bar to have certain colors and also define the mean value (the value in the middle) to be a same value for both plots.

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])))

这是输出:

这篇关于在ggplot2中为色条(图例)指定相同的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆