Hi folks,
I'm trying to add contours for the points in the following plot:
Pertinent code (removing theme
& other bumf) is:
natlanticextents <- data.frame(lon = c(-70, -55), lat = c(45, 51)) # GSL
extents <- sf::st_as_sf(natlanticextents, coords = c("lon","lat")) %>% sf::st_set_crs(4326)
library(marmap)
b = getNOAA.bathy(lon1 = natlanticextents[1,1], lon2 = natlanticextents[2,1], lat1 = natlanticextents[1,2], lat2 = natlanticextents[2,2], resolution = 4, keep = TRUE, path = paste0(machine, "Blocklab/MapData/getNOAAbathy/")) # get bathymetry data
bf = fortify.bathy(b) # convert bathymetry to data frame
ggplot() +
annotation_spatial(natlantic, fill = "grey", lwd = 0) + # wide background
layer_spatial(extents, size = 0, col = "white") + # trains scales
annotation_spatial(sf_points, # sf
aes(color = Stock)) + #colour on map & legend
geom_contour(data = bf, # add 200m contour
aes(x = x, y = y, z = z), breaks = c(-200), size = c(0.15), colour = "black") +
scale_colour_manual(values = c("blue", "red"))
I'm keen to add contours for the sf_points
using geom_density_2d
however the guides for this all reference simple x/y lat/lon column dataframes, rather than sf
objects. Subsequently I'm struggling to work out how to create these contours for sf_points
, which is an sf
object created by:
sf_points <- sf::st_as_sf(AnyDataFrame, coords = c("lon","lat")) %>% sf::st_set_crs(4326)
Various attempts:
geom_density_2d(data = sf_points, mapping = aes(geometry))
Error in is.finite(x) : default method not implemented for type 'list'
geom_density_2d(data = AnyDataFrame, mapping = aes(x = lon, y = lat))
Error in layer(data = data, mapping = mapping, stat = stat, geom = GeomDensity2d,: object 'lon' not found
geom_density_2d(data = AnyDataFrame, mapping = aes(Stock))
Error: Discrete value supplied to continuous scale
Am I trying to force a square peg into a round hole here? ggplot
elements typically understand sf
objects' projections natively, but geom_density_2d
requires x & y aesthetics which appear to need to be the x & y positions, which aren't available once converted to geometry
with sf::st_as_sf
.
Any insights very much appreciated - cheers in advance!