R:使用带有geom_tile()和scale_fill_gradientn()的颜色划分热图

时间:2018-11-30 22:33:55

标签: r ggplot2

我正在制作许多热图,它们应该具有相同的配色方案,如下所示:

  • 如果x轴值= y轴值,则用蓝色渐变填充
  • 如果x轴值> y轴值,则用黄色渐变填充
  • 如果x轴值

编辑:重要的是每种颜色在其各自的数字上渐变。也就是说,在下面的示例A中,18、20和25是地图上“最暗”的颜色。

我的代码如下:

library(ggplot2)
library(dplyr)
library(scales)
graphdata$pct <-ifelse(graphdata$A-graphdata$B>=0,graphdata$n/sum(graphdata$n),-graphdata$n/sum(graphdata$n))
graphdata$color_group <- ifelse(graphdata$A-graphdata$B<0,1,
                                   ifelse(graphdata$A-graphdata$B>0,2,3))
    graphdata$rescale <- 100*graphdata$pct + 100*(graphdata$color_group-1)
    gradientends <-c(min(graphdata$rescale),
                     ifelse(dim(subset(graphdata,rescale<=0,select=c(rescale)))[1]==0,0,max(subset(graphdata,rescale<=0,select=c(rescale)))),
                     ifelse(dim(subset(graphdata,rescale>=100 & rescale<200,select=c(rescale)))[1]==0,0,min(subset(graphdata,rescale>=100 & rescale<200,select=c(rescale)))),
                     ifelse(dim(subset(graphdata,rescale>=100 & rescale<200,select=c(rescale)))[1]==0,0,max(subset(graphdata,rescale>=100 & rescale<200,select=c(rescale)))),
                     ifelse(dim(subset(graphdata,rescale>=200,select=c(rescale)))[1]==0,0,min(subset(graphdata,rescale>=200,select=c(rescale)))),
                     max(graphdata$rescale))

    colorends <- c("tomato1","lightpink1","lightgoldenrod1","goldenrod1","lightsteelblue1","steelblue2")

    ggplot(data = graphdata, aes(x = as.factor(A), y = as.factor(B))) +
          geom_tile(aes(fill = rescale), colour = "white") + 
          scale_fill_gradientn(colors=colorends,values=rescale(gradientends)) +
          theme(legend.position = "none", 
                axis.text=element_text(size=12,face="bold"), 
                panel.background = element_blank(),
                axis.ticks=element_blank(), 
                plot.title = element_text(hjust=0.5)) + 
          geom_text(aes(label=n)) +labs(x="A",y="B")

当在所有三个类别中都可以进行存储的数据时,我的代码起作用(示例A),但是在数据中包含2个或更少类别时,它的颜色无法正确显示(示例B)。

示例A

A <- c(1,2,3,1,2,3,2,1,3)
B <- c(1,2,3,2,3,2,1,3,1)
n <- c(10,5,20,15,18,10,10,10,25)

graphdata <- data.frame(A,B,n)
rm(A,B,n)

给我我所期望的: enter image description here

示例B

A <- c(1,2,3)
B <- c(1,2,3)
n <- c(10,5,20)

graphdata <- data.frame(A,B,n)
rm(A,B,n)

不给我蓝色渐变: enter image description here

我希望示例B看起来更像这样: enter image description here

1 个答案:

答案 0 :(得分:2)

我建议您使用alpha缩放颜色。这使问题很多更简单:

cols <- c('-1' = "tomato1", '0' = "steelblue2", '1' = "goldenrod1")

ggplot(graphdata, aes(x = as.factor(A), y = as.factor(B))) +
    geom_tile(aes(fill = as.factor(sign(A-B)), alpha = n), colour = "white") + 
    scale_fill_manual(values = cols) +
    geom_text(aes(label = n)) +
    labs(x = "A", y = "B") +
    theme_minimal() + 
    theme(legend.position = 'none', panel.grid = element_blank())

enter image description here