Search code examples
r

Recreating a Heatmap in R


I am working with the R programming language.

I found these plots that I really like (https://link.springer.com/article/10.1007/s10902-020-00307-8) and want to try and recreate them:

enter image description here

Using the following link (https://jkzorz.github.io/2020/02/29/contour-plots.html), I tried to simulate some data and recreate the plots:

library(ggplot2)
library(reshape2)
library(metR)

set.seed(123)  
Biomass <- seq(0, 10, length.out = 100)
variable <- seq(0, 10, length.out = 100)

con <- data.frame(matrix(ncol = length(variable), nrow = length(Biomass)))

for (i in 1:length(Biomass)) {
    for (j in 1:length(variable)) {
        con[i, j] <- sin(Biomass[i]) + cos(variable[j])  # adjust this as needed
    }
}

rownames(con) <- Biomass

con <- cbind(Biomass = rownames(con), con)
rownames(con) <- NULL

con$Biomass <- as.numeric(con$Biomass)



conm = melt(con, id = "Biomass")
conm$variable <- gsub("X", "", conm$variable)
conm$variable = as.numeric(conm$variable)
gg = ggplot(conm, aes(x = variable, y = Biomass)) + 
    geom_raster(aes(fill = value)) + 
    geom_contour(aes(z = value), colour = "white", size = 0.2, alpha = 0.5) + 
    geom_text_contour(aes(z = value),  colour = "white" ) +
    labs(x = "Filtered light intensity (umol photons/m2/s)", 
         y = "Dry Biomass Concentration (g/L)", 
         fill = "Productivity (umol O2/g biomass/s)") + 
    theme(legend.title = element_text(size = 10, face = "bold"), 
          legend.position = "top", panel.background = element_blank(), 
          axis.text = element_text(colour = "black", size = 10, face = "bold"), 
          axis.title = element_text(size = 12, face = "bold"), 
          legend.text = element_text(size = 11), legend.key = element_blank()) + 
    scale_fill_continuous(low = "#BFE1B0", high = "#137177") + 
    scale_y_continuous(expand = c(0,0)) +
    scale_x_continuous(expand = c(0,0)) 

gg

enter image description here

Is it possible to recreate the color scheme?

Thanks!


Solution

  • The color scheme looks like the RdYlGn palette available in the package RColorBrewer. To use that palette for your continuous data, you can create a function that interpolates the the color values:

    my_colors <- colorRampPalette(RColorBrewer::brewer.pal(11, "RdYlGn"))

    Overwriting the fill aesthetic in your example gives a good approximation of the colors of the reference figure:

    gg + scale_fill_gradientn(colors = my_colors(10))

    enter image description here