library(sp)
library(rnaturalearth)
library(rnaturalearthdata)
library(tidyverse)
library(geosphere)
library(rgeos)
#' @export
plot_reefish_survey <- function (reefishSurveyEnvSocio, clusterDistanceThreshold=500) {
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")
coords <- data.frame(lon = reefishSurveyEnvSocio$SiteLongitude,
lat = reefishSurveyEnvSocio$SiteLatitude)
# convert data to a SpatialPointsDataFrame object
xy <- sp::SpatialPointsDataFrame(
coords, data.frame(ID=seq(1:length(coords$lon))),
proj4string=sp::CRS("+proj=longlat +ellps=WGS84 +datum=WGS84"))
# use the distm function to generate a geodesic distance matrix in meters
mdist <- geosphere::distm(xy)
# cluster all points using a hierarchical clustering approach
hc <- hclust(as.dist(mdist), method="complete")
# define the distance threshold, in this case 500,000 m
d=clusterDistanceThreshold*1000
# define clusters based on a tree "height" cutoff "d" and add them to the SpDataFrame
xy$clust <- cutree(hc, h=d)
## centroid
cent <- matrix(ncol=3, nrow=max(xy$clust))
for (i in 1:max(xy$clust)) {
# gCentroid from the rgeos package
cent[i,c(1,2)] <- rgeos::gCentroid(subset(xy, clust == i))@coords
cent[i,3] <- length(which(xy$clust == i))
}
## dataframe to plot
dfc <- data.frame(longitude=cent[,1],
latitude=cent[,2],
numberOfSurveys= cent[,3]
)
## plot world map and centroids surveys
gg <- ggplot2::ggplot(data=world)+
ggplot2::geom_sf()+
ggplot2::geom_point(data = dfc,
ggplot2::aes(x = longitude,
y = latitude,
color=numberOfSurveys
), size = 2)+
ggplot2::scale_color_gradient(low = 'yellow', high = 'red')+
ggplot2::theme(panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.background = ggplot2::element_rect(fill = "lightblue",
colour = "lightblue")
)
return(gg)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.