简体   繁体   English

使用scale_colour_gradient自定义ggplot热图中的颜色

[英]Customize colors in ggplot heatmap using scale_colour_gradient

I'm trying to plot a Pearson pairwise correlation heatmap using ggplot2 and scale_colour_gradient . 我正在尝试使用ggplot2scale_colour_gradient绘制皮尔逊成对相关heatmap

Here are my example data: 这是我的示例数据:

library(dplyr)
library(ggplot2)
set.seed(1)

pairs.mat <- t(combn(1:5,2))
df <- data.frame(sample1=pairs.mat[,1],sample2=pairs.mat[,2]) %>% dplyr::mutate(association=runif(10,0.85,1))

Here's the ggplot2 code I'm trying: 这是我正在尝试的ggplot2代码:

heatmap.ggplot <- ggplot(df,aes(sample1,sample2,fill=association))+geom_tile(color="white")+
  scale_colour_gradient(low="gray",high="red",limit=c(min(df$association),1),space="Lab",guide="colourbar")+theme_minimal()+
  theme(axis.title.x=element_blank(),axis.title.y=element_blank(),axis.text.x=element_text(angle=45,vjust=1,size=12,hjust=1))+coord_fixed()+coord_flip()+labs(colors="Cor")

which produces: 产生: 在此处输入图片说明

My questions are: 我的问题是:

  1. I specify the range to be low="gray" and high="red" but I'm getting the elements in the blue range. 我将范围指定为low="gray"high="red"但是我将元素设置为蓝色范围。 How do I fix that? 我该如何解决?
  2. I can't seem to change the legend title using the labs(colors="Cor") . 我似乎无法使用labs(colors="Cor")更改图例标题。 Any idea about that? 有什么想法吗?

Thanks 谢谢

You need scale_fill_gradient . 您需要scale_fill_gradient

ggplot(df, aes(sample1, sample2, fill = association)) +
  geom_tile(color = "white") +
  scale_fill_gradient(
    name = "Cor", # changes legend title
    low = "gray",
    high = "red",
    limit = c(min(df$association), 1),
    space = "Lab",
    guide = "colourbar"
  ) + theme_minimal() +
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    axis.text.x = element_text(
      angle = 45,
      vjust = 1,
      size = 12,
      hjust = 1
    )
  ) + 
coord_fixed() + 
coord_flip() 

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM