Home > Software design >  Highlight area of interest in ggplot raster
Highlight area of interest in ggplot raster

Time:11-04

I'd like to indicate an area of interest in a heatmap or raster plotted using ggplot2. My use case is not spatial data but continuous data with three variables. I've come up with a solution using the terra package, but I think there must be a more elegant or simple solution out there. In the example, below I use polygons to indicate areas with values of some threshold I chose.

library(ggplot2)
library(dplyr)
library(terra)

data("faithfuld")

# rasterize the data with terra
ncol <- faithfuld |> distinct(waiting) |> nrow()
nrow <- faithfuld |> distinct(eruptions) |> nrow()
xmin <- faithfuld$waiting |> min()
xmax <- faithfuld$waiting |> max()
ymin <- faithfuld$eruptions |> min()
ymax <- faithfuld$eruptions |> max()

faithful_vec <- vect(faithfuld, geom = c("waiting", "eruptions"))

r1 <- rast(ncol=ncol, nrow=nrow, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
r1 <- rasterize(faithful_vec, r1, "density", mean)

# filter values to highlight
r1[r1 < 0.025] <- NA

# convert to polygon and grab geometry
r2 <- as.polygons(r1) |> 
  geom() |> 
  as_tibble()

ggplot()  
  geom_raster(data = faithfuld, aes(waiting, eruptions, fill = density), interpolate = TRUE)  
  ## highlighted area ##
  geom_polygon(data = r2, aes(x, y, group = part), color = "white", fill = "transparent")  
  scale_fill_viridis_c()

heatmap

Ideally, I'd like a solution without relying on terra to generate the polygons.

CodePudding user response:

You can use geom_contour directly for this purpose, setting a single break at 0.025. It also has the benefit of smoothing the result by interpolation.

library(ggplot2)
library(dplyr)

data("faithfuld")

faithfuld %>%
  ggplot(aes(eruptions, waiting, fill = density))  
  geom_raster(interpolate = TRUE)  
  scale_fill_viridis_c()  
  geom_contour(aes(z = density), color = "white", breaks = 0.025)

enter image description here

  • Related