I want to draw the heatmap while setting the customized range of values.
Since the original data has large range of values, I set the limitation of coloring by Q1, Q3, and IQR.
In this case, the range of colorbar should be slightly different as below.
# Example data from https://r-charts.com/correlation/heat-map-ggplot2/
set.seed(8)
m <- matrix(round(rnorm(200), 2), 10, 10)
colnames(m) <- paste("Col", 1:10)
rownames(m) <- paste("Row", 1:10)
# Transform the matrix in long format
df <- melt(m)
colnames(df) <- c("x", "y", "value")
# Plain heatmap
ggplot(df, aes(x=x, y=y, fill=value))+
geom_tile()+
theme_bw()+
theme(axis.text.x = element_blank(),
axis.title.y = element_blank(),
legend.key.height=unit(0.175, 'npc'),
legend.position='left',
legend.title=element_blank(),
legend.margin = margin(0,0,0,0),
strip.text=element_text(size=13))
# Customized heatmap
ggplot(df, aes(x=x, y=y, fill=value))+
geom_tile()+
scale_fill_gradientn(colours = c('#F2F8F9', '#5696AF', '#072238'),
limits=range(-0.09843, 0.811008), oob = scales::squish)+ #Quantiles
scale_colour_gradientn(guide='colorbar',
colors=c('#F2F8F9', '#5696AF', '#072238'),
limits=c(-0.1, 2))+ #Colorbar range
scale_y_discrete(position = "right")+
theme_bw()+
theme(axis.text.x = element_blank(),
axis.title.y = element_blank(),
legend.key.height=unit(0.175, 'npc'),
legend.position='left',
legend.title=element_blank(),
legend.margin = margin(0,0,0,0),
strip.text=element_text(size=13))
I guess the correct result should be like this plot.
((-3,2) is the real range of values and (-0.9,0.8) is the cutoff value for the coloring.
Although I set the two limits in the last code, but the second one was ignored.
Please ignore the number of ticks in the colorbar. I want it to automatically set considring the real range.
Simply, I added labels
parameter in the scale_fill_gradientn
matching the number of ticks and labels.
...
scale_fill_gradientn(colours = c('#F2F8F9', '#5696AF', '#072238'),
limits=range(-0.09843, 0.811008), oob = scales::squish,
labels=c(-0.1, 0.53, 1.13, 1.76, 2))+
...