简体   繁体   中英

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 .

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:

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. How do I fix that?
  2. I can't seem to change the legend title using the labs(colors="Cor") . Any idea about that?

Thanks

You need 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() 

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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