knitr::opts_chunk$set(echo = TRUE)
# Load libraries library(raster) library(ggplot2) library(leaflet) library(dplyr) library(remotes) # Install ohwobpg package installed <- rownames(installed.packages()) if (!("ohwobpg" %in% installed)) remotes::install_github("BigelowLab/ohwobpg", quiet = TRUE) # Load ohwobpg package library(ohwobpg)
Once the necessary packages are loaded, we will start by creating a raster object from a pre-loaded ohwobpg database. Specifically, we will be creating a raster object of sea surface temperature (SST) data for June of 2018.
# Load database path <- system.file("gom", package = "ohwobpg") db <- read_database(path) # Subset database par_db <- db %>% dplyr::filter(param == "sst" & per == "MO" & dplyr::between(date, as.Date("2018-05-15"), as.Date("2018-09-26"))) # Create raster stack par <- par_db %>% # start with the subset database as_filename(path = path) %>% # build filenames and append to the path raster::stack() # read them into a stack of images # Name layers names(par) <- format(par_db$date, "%b") # Isolate June r <- par$Jun
Next, we will plot the June 2018 SST raster object using the base R plot() function. We simply call the plot() function with the raster object as the argument. For more options to make fancier plots with base plot and a more detailed example, see https://www.neonscience.org/dc-plot-raster-data-r.
plot(r)
Next, we will plot the same raster object using the package ggplot2. First, the user needs to convert the raster object to a dataframe with coordinates, using as.data.frame(raster, xy = TRUE). Next, the dataframe can be plotted using geom_tile(). For an in-depth example of how to plot a raster using ggplot2 and geom_tile(), see https://ggplot2.tidyverse.org/reference/geom_tile.html.
# Convert raster to dataframe r_df <- as.data.frame(r, xy = TRUE) # Plot dataframe using ggplot2 ggplot(data = r_df, mapping = aes(x = x, y = y, color = Jun, fill = Jun)) + # Add raster data geom_tile() + # Change NA fill color to white scale_fill_continuous(na.value = "white") + scale_color_continuous(na.value = "white") + # Add axes labels labs(x = "Lon", y = "Lat")
Finally, we will plot the raster object on a leaflet interactive map. The leaflet::addRasterImage() function allows the user to plot raster objects on the map. For a more detailed example, see https://rstudio.github.io/leaflet/raster.html.
leaflet::leaflet() %>% leaflet::addTiles(group = "Standard") %>% # Add satellite imagery leaflet::addProviderTiles('Esri.WorldImagery', group = "Satellite") %>% # Define bounds leaflet::fitBounds(lng1 = min(r_df$x), lat1 = min(r_df$y), lng2 = max(r_df$x), lat2 = max(r_df$y)) %>% # Add raster data leaflet::addRasterImage(r)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.