R ggplot2热图固定图之间的比例颜色

时间:2017-06-20 14:23:20

标签: r ggplot2 colors heatmap

我需要绘制3个不同的图,设置相同的比例范围颜色。 我有3个不同范围的矩阵。

例如:

range(matrixA) 
# 0.60 0.85  
range(matrixB) 
# 0.65 0.95  
range(matrixA) 
# 0.5 1.0

我想为这些情节填充相同的颜色。例如,对于差异图中的所有0.8值,如果在第一个图中0.8橙色,我希望不同图中的所有0.8值都是相同的橙色。

我现在的问题是:

在第一个图中,最大值的颜色为红色,则值0.85为红色。

在第二个图中,最大值为红色,但在这种情况下,最大值为0.95并且出现问题。

我的代码:

mat.melted <- melt(matrixA)
colnames(mat.melted) <- c("p","c","v")
p <- ggplot(mat.melted, aes(x=c,y=p,fill=v) + 
         geom-tile() + 
         scale_fill_gradintn(limits = c(min(as.vector(matrixA)), max(as.vector(matrixA))), 
                             colors = c("yellow","orange","red"))

2 个答案:

答案 0 :(得分:3)

您需要为所有这些设置相同的范围(颜色条的限制),并为其指定颜色。

rng = range(matrixA, matrixB, matrixC)

并将其添加到您的ggplot代码中:

g + scale_fill_gradient2(low="green", mid="lightblue", high="red", #colors in the scale
               midpoint=mean(rng),    #same midpoint for plots (mean of the range)
               breaks=seq(0,1,0.25), #breaks in the scale bar
               limits=c(floor(rng[1]), ceiling(rng[2])))

实施例

以下示例可帮助您获得所需内容:

x <- matrix(60:85, 5)/100
y <- matrix(65:95, 5)/100
z <- matrix(50:100, 5)/100


rng = range(c((x), (y), (z)))

library(reshape)
library(ggplot2)

ggplot(data = melt(x)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
  scale_fill_gradient2(low="green", mid="lightblue", high="red", #colors in the scale
                   midpoint=mean(rng),    #same midpoint for plots (mean of the range)
                   breaks=seq(0,1,0.25), #breaks in the scale bar
                   limits=c(floor(rng[1]), ceiling(rng[2]))) + #same limits for plots
                   ggtitle("X")

ggplot(data = melt(y)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
  scale_fill_gradient2(low="green", mid="lightblue", high="red", 
                   midpoint=mean(rng),   
                   breaks=seq(0,1,0.25), 
                   limits=c(floor(rng[1]), ceiling(rng[2]))) +
                    ggtitle("Y")                  

ggplot(data = melt(z)) + geom_tile(aes(x=X1,y=X2,fill = value)) +
 scale_fill_gradient2(low="green", mid="lightblue", high="red", 
                   midpoint=mean(rng),    
                   breaks=seq(0,1,0.25), 
                   limits=c(floor(rng[1]), ceiling(rng[2]))) +
                    ggtitle("Z")   

这会给你:

答案 1 :(得分:0)

将限制设置在0.5和1之间

mat.melted <- melt(matrixA)
colnames(mat.melted) <- c("p","c","v")
p <- ggplot(mat.melted, aes(x=c,y=p,fill=v) + 
         geom-tile() + 
         scale_fill_gradintn(colors = c("yellow","orange","red")),limits=c(0.5,1))