0

I want to create a heatmap with the code below.

data_smoothed = ggplot() +
  metR::geom_contour_fill(data = data.dolphins, aes(x = lon, y = lat, z = density), 
                          bins = 120, na.fill = TRUE)+
  coord_sf(xlim = c(-1, 5), ylim = c(37,43))+ #I want to change this 
  scale_fill_viridis_c() +
  metR::scale_x_longitude(ticks = 2)+
  metR::scale_y_latitude(ticks=2)+
  theme_bw() +
  ggtitle("dolphins")+
  theme(plot.title = element_text(hjust = 0.5)) 

which returns this: enter image description here

However, instead of receiving this, I would only like to keep these parts of the heatmap that fall within a multipolygon I already have.

> poly
Simple feature collection with 1 feature and 0 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -1 ymin: 37 xmax: 6 ymax: 42.42764
Geodetic CRS:  WGS 84
                        geometry
1 MULTIPOLYGON (((0.5 39.5, 0...

i.e something like the parts of the heatmap that fall within the poygon shown below. enter image description here

Any ideas?

geke94
  • 1
  • 1

1 Answers1

0

It seems this thread did something similar ggplot2/gis Plotting inside polygon area I've also done something similar in the past using st_intersection() from the sf package, to filter the data that overlaps with your polygon before you plot.

LGen
  • 1
  • I've seen this post before. My data points are actually within the multipolygon. So I think it's more an interpolation matter or of how to present the data. – geke94 Nov 10 '21 at 13:05
  • I see, would simply plotting your polygon on top of your data achieve the look you want? I'm not sure I understand what you want :) – LGen Nov 10 '21 at 13:34
  • No, I would like only the area inside the polygon to be colored. Thanks for your help :) – geke94 Nov 10 '21 at 13:44