Search code examples
rgeom-text

How do you format the text displayed by geom_text_contour?


MWE:

library(metR)

heat_palette = c("darkred", "red", "yellow", "#00A600", "darkgreen")

heatmap_of_percentage <- function(percent) {
  # display <- sprintf("%2f%%", {{percent}})  
  # ^^ If I uncomment this, I get a bug
  c(
    geom_raster(aes(fill = {{percent}})),
    geom_contour(aes(z = {{percent}}), color = "black"),
    geom_text_contour(aes(z = {{percent}}), color = "black", stroke = 0.2),
    scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
  )
}
  
df <- expand.grid(x = 1:100, y = 1:100)
df$Z <- df$x * df$y / 100

ggplot(df, aes(x = x, y = y)) + 
  heatmap_of_percentage(percent = Z)

produces

enter image description here

I would like to modify this so that the contours are labelled 10%, 30%, etc.. How can I do this, only modifying heatmap_of_percentage (i.e. not adding an extra column in the calling code)?


Solution

  • You could use after_stat() to format the labels which correspond to the value of level which is computed by geom_text_contour under the hood:

    library(metR)
    library(ggplot2)
    
    heat_palette <- c("darkred", "red", "yellow", "#00A600", "darkgreen")
    
    heatmap_of_percentage <- function(percent) {
      c(
        geom_raster(aes(fill = {{ percent }})),
        geom_contour(aes(z = {{ percent }}), color = "black"),
        geom_text_contour(
          aes(
            z = {{ percent }},
            label = after_stat(sprintf("%.0f%%", level))
          ),
          color = "black", stroke = 0.2
        ),
        scale_fill_gradientn(limits = c(0, 100), colours = heat_palette)
      )
    }
    
    df <- expand.grid(x = 1:100, y = 1:100)
    df$Z <- df$x * df$y / 100
    
    ggplot(df, aes(x = x, y = y)) +
      heatmap_of_percentage(percent = Z)