【问题标题】:Specifying same limits for colorbar (legend) in ggplot2在 ggplot2 中为颜色条(图例)指定相同的限制
【发布时间】:2017-06-01 18:01:27
【问题描述】:

我希望多个图共享相同的色阶。一个图中的给定值应与第二个图中的颜色相同。如何使用 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))

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

【问题讨论】:

    标签: r plot ggplot2 heatmap


    【解决方案1】:

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

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

    这是输出:

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多