OCEANA Demo

This is an R Markdown document of the Oceana demo data from Anne & Katie

Basic Stuff loaded + data clean

# Load all 
libraries <- c("sp", "devtools", "ggplot2", "dplyr",
               "scales", "rgeos", "rgdal", "ggalt",
               "grid", "cowplot", "raster", "plyr", "sf",
               "ggspatial", "readr", "lubridate")
lapply(libraries, library, character.only = TRUE)
## The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
## which was just loaded, will retire in October 2023.
## Please refer to R-spatial evolution reports for details, especially
## https://r-spatial.org/r/2023/05/15/evolution4.html.
## It may be desirable to make the sf package available;
## package maintainers should consider adding sf to Suggests:.
## The sp package is now running under evolution status 2
##      (status 2 uses the sf package in place of rgdal)
## Loading required package: usethis
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
## rgeos version: 0.6-4, (SVN revision 699)
##  GEOS runtime version: 3.11.0-CAPI-1.17.0 
##  Please note that rgeos will be retired during October 2023,
## plan transition to sf or terra functions using GEOS at your earliest convenience.
## See https://r-spatial.org/r/2023/05/15/evolution4.html for details.
##  GEOS using OverlayNG
##  Linking to sp version: 2.0-0 
##  Polygon checking: TRUE
## 
## Attaching package: 'rgeos'
## The following object is masked from 'package:dplyr':
## 
##     symdiff
## Please note that rgdal will be retired during October 2023,
## plan transition to sf/stars/terra functions using GDAL and PROJ
## at your earliest convenience.
## See https://r-spatial.org/r/2023/05/15/evolution4.html and https://github.com/r-spatial/evolution
## rgdal: version: 1.6-7, (SVN revision 1203)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 3.5.3, released 2022/10/21
## Path to GDAL shared files: /Users/colby_kresge/Library/R/arm64/4.3/library/rgdal/gdal
##  GDAL does not use iconv for recoding strings.
## GDAL binary built with GEOS: TRUE 
## Loaded PROJ runtime: Rel. 9.1.0, September 1st, 2022, [PJ_VERSION: 910]
## Path to PROJ shared files: /Users/colby_kresge/Library/R/arm64/4.3/library/rgdal/proj
## PROJ CDN enabled: FALSE
## Linking to sp version:1.6-1
## To mute warnings of possible GDAL/OSR exportToProj4() degradation,
## use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
## Registered S3 methods overwritten by 'ggalt':
##   method                  from   
##   grid.draw.absoluteGrob  ggplot2
##   grobHeight.absoluteGrob ggplot2
##   grobWidth.absoluteGrob  ggplot2
##   grobX.absoluteGrob      ggplot2
##   grobY.absoluteGrob      ggplot2
## 
## Attaching package: 'raster'
## The following object is masked from 'package:dplyr':
## 
##     select
## ------------------------------------------------------------------------------
## You have loaded plyr after dplyr - this is likely to cause problems.
## If you need functions from both plyr and dplyr, please load plyr first, then dplyr:
## library(plyr); library(dplyr)
## ------------------------------------------------------------------------------
## 
## Attaching package: 'plyr'
## The following objects are masked from 'package:dplyr':
## 
##     arrange, count, desc, failwith, id, mutate, rename, summarise,
##     summarize
## Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
## 
## Attaching package: 'readr'
## The following object is masked from 'package:scales':
## 
##     col_factor
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:raster':
## 
##     intersect, union
## The following object is masked from 'package:cowplot':
## 
##     stamp
## The following objects are masked from 'package:rgeos':
## 
##     intersect, setdiff, union
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
## [[1]]
## [1] "sp"        "stats"     "graphics"  "grDevices" "utils"     "datasets" 
## [7] "methods"   "base"     
## 
## [[2]]
##  [1] "devtools"  "usethis"   "sp"        "stats"     "graphics"  "grDevices"
##  [7] "utils"     "datasets"  "methods"   "base"     
## 
## [[3]]
##  [1] "ggplot2"   "devtools"  "usethis"   "sp"        "stats"     "graphics" 
##  [7] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[4]]
##  [1] "dplyr"     "ggplot2"   "devtools"  "usethis"   "sp"        "stats"    
##  [7] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[5]]
##  [1] "scales"    "dplyr"     "ggplot2"   "devtools"  "usethis"   "sp"       
##  [7] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [13] "base"     
## 
## [[6]]
##  [1] "rgeos"     "scales"    "dplyr"     "ggplot2"   "devtools"  "usethis"  
##  [7] "sp"        "stats"     "graphics"  "grDevices" "utils"     "datasets" 
## [13] "methods"   "base"     
## 
## [[7]]
##  [1] "rgdal"     "rgeos"     "scales"    "dplyr"     "ggplot2"   "devtools" 
##  [7] "usethis"   "sp"        "stats"     "graphics"  "grDevices" "utils"    
## [13] "datasets"  "methods"   "base"     
## 
## [[8]]
##  [1] "ggalt"     "rgdal"     "rgeos"     "scales"    "dplyr"     "ggplot2"  
##  [7] "devtools"  "usethis"   "sp"        "stats"     "graphics"  "grDevices"
## [13] "utils"     "datasets"  "methods"   "base"     
## 
## [[9]]
##  [1] "grid"      "ggalt"     "rgdal"     "rgeos"     "scales"    "dplyr"    
##  [7] "ggplot2"   "devtools"  "usethis"   "sp"        "stats"     "graphics" 
## [13] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[10]]
##  [1] "cowplot"   "grid"      "ggalt"     "rgdal"     "rgeos"     "scales"   
##  [7] "dplyr"     "ggplot2"   "devtools"  "usethis"   "sp"        "stats"    
## [13] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[11]]
##  [1] "raster"    "cowplot"   "grid"      "ggalt"     "rgdal"     "rgeos"    
##  [7] "scales"    "dplyr"     "ggplot2"   "devtools"  "usethis"   "sp"       
## [13] "stats"     "graphics"  "grDevices" "utils"     "datasets"  "methods"  
## [19] "base"     
## 
## [[12]]
##  [1] "plyr"      "raster"    "cowplot"   "grid"      "ggalt"     "rgdal"    
##  [7] "rgeos"     "scales"    "dplyr"     "ggplot2"   "devtools"  "usethis"  
## [13] "sp"        "stats"     "graphics"  "grDevices" "utils"     "datasets" 
## [19] "methods"   "base"     
## 
## [[13]]
##  [1] "sf"        "plyr"      "raster"    "cowplot"   "grid"      "ggalt"    
##  [7] "rgdal"     "rgeos"     "scales"    "dplyr"     "ggplot2"   "devtools" 
## [13] "usethis"   "sp"        "stats"     "graphics"  "grDevices" "utils"    
## [19] "datasets"  "methods"   "base"     
## 
## [[14]]
##  [1] "ggspatial" "sf"        "plyr"      "raster"    "cowplot"   "grid"     
##  [7] "ggalt"     "rgdal"     "rgeos"     "scales"    "dplyr"     "ggplot2"  
## [13] "devtools"  "usethis"   "sp"        "stats"     "graphics"  "grDevices"
## [19] "utils"     "datasets"  "methods"   "base"     
## 
## [[15]]
##  [1] "readr"     "ggspatial" "sf"        "plyr"      "raster"    "cowplot"  
##  [7] "grid"      "ggalt"     "rgdal"     "rgeos"     "scales"    "dplyr"    
## [13] "ggplot2"   "devtools"  "usethis"   "sp"        "stats"     "graphics" 
## [19] "grDevices" "utils"     "datasets"  "methods"   "base"     
## 
## [[16]]
##  [1] "lubridate" "readr"     "ggspatial" "sf"        "plyr"      "raster"   
##  [7] "cowplot"   "grid"      "ggalt"     "rgdal"     "rgeos"     "scales"   
## [13] "dplyr"     "ggplot2"   "devtools"  "usethis"   "sp"        "stats"    
## [19] "graphics"  "grDevices" "utils"     "datasets"  "methods"   "base"
setwd("/Users/colby_kresge/Desktop/Working R ")

########## SECTION 1: COMPLETE THE CODE ##########

#' This section involves plotting a vessel's activity using the ggplot package.

## Read in data for vessel tracks (tracks.csv) and events (voyage_events.csv)
vessel_events<- read_csv("short_map_ex_debug/voyage_events.csv")
## New names:
## • `` -> `...1`
## Rows: 64 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (3): event_type, anchorage_name, anchorage_country
## dbl  (5): ...1, vessel_1_id, lat, lon, event_duration_hr
## lgl  (1): vessel_2_id
## dttm (2): event_start, event_end
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
tracks<- read_csv("short_map_ex_debug/tracks.csv")
## New names:
## Rows: 24299 Columns: 5
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (1): timestamp dbl (4): ...1, mmsi, lat, lon
## ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
## Specify the column types or set `show_col_types = FALSE` to quiet this message.
## • `` -> `...1`
#####
## Some of the points in tracks.csv contain nonsensical values in the lat and lon columns.
## WITHOUT manually inspecting the csv file, please describe below how you would identify these points 
## and remove them from the tracks dataframe. Please note that you do not need to do actually remove these
## data points, but just need to provide an short explanation (commented below here) of what you would want to look for

# check it out 
glimpse(tracks)
## Rows: 24,299
## Columns: 5
## $ ...1      <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1…
## $ mmsi      <dbl> 224892000, 224892000, 224892000, 224892000, 224892000, 22489…
## $ lat       <dbl> -22.45102, -22.43392, -22.39616, -22.38539, -22.38088, -22.3…
## $ lon       <dbl> -78.13587, -78.13313, -78.12646, -78.12450, -78.12363, -78.1…
## $ timestamp <chr> "6/2/2017 0:08", "6/2/2017 0:16", "6/2/2017 0:34", "6/2/2017…
sum(is.na(tracks$lat))
## [1] 1
sum(is.na(tracks$lon))
## [1] 2
# Omit NA lat // lon 
tracks_clean <- tracks %>%
  filter(!is.na(lat) & !is.na(lon))

# summary(tracks)
min(tracks_clean$lat)
## [1] -60
max(tracks_clean$lon)
## [1] -74.33777
summary(tracks_clean)
##       ...1            mmsi                lat              lon         
##  Min.   :    1   Min.   :224892000   Min.   :-60.00   Min.   :-100.00  
##  1st Qu.: 6077   1st Qu.:224892000   1st Qu.:-21.83   1st Qu.: -78.04  
##  Median :12151   Median :224892000   Median :-21.41   Median : -77.87  
##  Mean   :12151   Mean   :224892000   Mean   :-20.57   Mean   : -77.24  
##  3rd Qu.:18225   3rd Qu.:224892000   3rd Qu.:-20.88   3rd Qu.: -77.16  
##  Max.   :24299   Max.   :224892000   Max.   :100.00   Max.   : -74.34  
##   timestamp        
##  Length:24297      
##  Class :character  
##  Mode  :character  
##                    
##                    
## 
plot(tracks_clean$lat~tracks_clean$lon)

# Couple that are far out, lat = > 50 and less than -50 nonsensical 


tracks_clean <- tracks %>%
  filter(lat <= 50 & lat >= -50)


plot(tracks_clean$lat~tracks_clean$lon)

# Looks fine now 


## Read in land and eez shapefiles from working directory (nothing for you to do in this section)
#
land <- st_read(
  "short_map_ex_debug/ne_10m_land.shp")
## Reading layer `ne_10m_land' from data source 
##   `/Users/colby_kresge/Desktop/Working R /short_map_ex_debug/ne_10m_land.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 10 features and 3 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -180 ymin: -90 xmax: 180 ymax: 83.6341
## Geodetic CRS:  WGS 84
eez<- st_read(
  "short_map_ex_debug/World_EEZ_v8_20140228_LR/World_EEZ_v8_2014.shp")
## Reading layer `World_EEZ_v8_2014' from data source 
##   `/Users/colby_kresge/Desktop/Working R /short_map_ex_debug/World_EEZ_v8_20140228_LR/World_EEZ_v8_2014.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 249 features and 15 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -180 ymin: -85.47029 xmax: 180 ymax: 87.02394
## Geodetic CRS:  WGS 84
land_df <- fortify(land)
eez_df <- fortify(eez)


## Fill in code on right side of '<-' to create new dataframes that are subset from vessel_events  
## dataframe for 'fishing' and 'anchorage' events

View(vessel_events)

fishing <- vessel_events %>%
  filter(event_type == "fishing")

# Subset the data frame for anchorage events
anchorage <- vessel_events %>%
  filter(event_type == "anchorage")


cols<-c('tracks'='#696969','fishing'='green','anchorage'='red')
## Create list of shapes so that tracks has no shape, and fishing and anchorage are both solid circles



#shps<-
shps <- list(
  tracks = NA,        # No shape for tracks
  fishing = 16,       # Solid circle for fishing
  anchorage = 16      # Solid circle for anchorage
)

## Create list of line types below so that tracks is a solid line and fishing
## and anchorage events are blank lines

# Create a list of line types
ln <- c('solid', 'blank', 'blank')

# Assign labels to line types
names(ln) <- c('tracks', 'fishing', 'anchorage')


label=c('tracks','fishing','anchorage')

## Create a string for the chart title with a line break between the ship name and MMSI

# Example ship name and MMSI
ship_name <- "Ship Name"
mmsi <- "123456789"

# Create the chart title string with a line break
chart_title <- paste(ship_name, "\n", mmsi)

print(chart_title)
## [1] "Ship Name \n 123456789"
## Use ggplot to create the map. geom_polygon are used to the land and EEZ dataframes, 
## geom_path is used for track data, and geom_point is used for anchorage and fishing events
## The tracks, fishing points, and anchorage points are missing from the below map, add them

glimpse(fishing)
## Rows: 63
## Columns: 11
## $ ...1              <dbl> 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18…
## $ event_type        <chr> "fishing", "fishing", "fishing", "fishing", "fishing…
## $ vessel_1_id       <dbl> 224892000, 224892000, 224892000, 224892000, 22489200…
## $ vessel_2_id       <lgl> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, …
## $ anchorage_name    <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, …
## $ anchorage_country <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, …
## $ lat               <dbl> -22.2848, -21.8146, -21.8264, -21.7447, -21.7393, -2…
## $ lon               <dbl> -78.3230, -78.3637, -78.1114, -77.9397, -77.9582, -7…
## $ event_start       <dttm> 2017-06-01 00:20:27, 2017-06-01 09:08:06, 2017-06-0…
## $ event_end         <dttm> 2017-06-01 03:08:37, 2017-06-02 04:16:52, 2017-06-0…
## $ event_duration_hr <dbl> 2.80277778, 19.14611111, 19.69722222, 0.68222222, 6.…
glimpse(tracks_clean)
## Rows: 24,296
## Columns: 5
## $ ...1      <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1…
## $ mmsi      <dbl> 224892000, 224892000, 224892000, 224892000, 224892000, 22489…
## $ lat       <dbl> -22.45102, -22.43392, -22.39616, -22.38539, -22.38088, -22.3…
## $ lon       <dbl> -78.13587, -78.13313, -78.12646, -78.12450, -78.12363, -78.1…
## $ timestamp <chr> "6/2/2017 0:08", "6/2/2017 0:16", "6/2/2017 0:34", "6/2/2017…
tracks_clean <- tracks_clean %>%
  mutate(timestamp = mdy_hm(timestamp),
         date = as.Date(timestamp))
# set up 
library(rnaturalearth)
## Support for Spatial objects (`sp`) will be deprecated in {rnaturalearth} and will be removed in a future release of the package. Please use `sf` objects with {rnaturalearth}. For example: `ne_download(returnclass = 'sf')`
library(rnaturalearthdata)
## 
## Attaching package: 'rnaturalearthdata'
## The following object is masked from 'package:rnaturalearth':
## 
##     countries110
bg = ne_countries(scale = 'medium', returnclass = 'sf')
# 


library(ggplot2)
library(plotly)
## 
## Attaching package: 'plotly'
## The following objects are masked from 'package:plyr':
## 
##     arrange, mutate, rename, summarise
## The following object is masked from 'package:raster':
## 
##     select
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(leaflet)
library(htmlwidgets)  


# Define the ggplot without the legend
plot1 <- ggplot() +
  geom_sf(data = eez_df, aes(color = "EEZ")) +
  geom_sf(data = land_df, aes(color = "Land")) +
  geom_path(data = tracks_clean, aes(x = lon, y = lat, color = "Tracks"), size = 1) +
  geom_point(data = fishing, aes(x = lon, y = lat, color = "Fishing"), shape = 20, size = 1) +
  geom_point(data = anchorage, aes(x = lon, y = lat, color = "Anchorage"), shape = 20, size = 3) +
  geom_sf(data = bg, fill = "cornsilk3") +
  coord_sf(xlim = c(-87, -60), ylim = c(-30, 0)) +
  labs(title = chart_title, x = 'Longitude', y = 'Latitude') +
  scale_color_manual(values = c("EEZ" = "lightgrey", "Land" = "cornsilk3", "Tracks" = "green", 
                                "Fishing" = "red", "Anchorage" = "yellow", "Background" = "cornsilk3")) +
  theme(panel.grid.major = element_line(color = gray(0.5), linetype = "blank", size = 0.3),
        panel.background = element_rect(color = gray(0.5), fill = 'lightblue2'),
        legend.position = "none") #+  # Remove the legend
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
## ℹ Please use the `linewidth` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
  #annotation_north_arrow(which_north = "true", height = unit(0.5, 'cm'),
   #                      width = unit(0.5, 'cm'))

# Convert ggplot to interactive plotly object
plotly_map <- ggplotly(plot1)
leaflet_map <- as_widget(plotly_map)

leaflet_map
## ggOceanMaps: Setting data download folder to a temporary folder
## /var/folders/3h/gxw7tj4n4j18npdyfbj9pm3h0000gs/T//RtmpKDfrNe. This
## means that any downloaded map data need to be downloaded again when you
## restart R. To avoid this problem, change the default path to a
## permanent folder on your computer. Add following lines to your
## .Rprofile file: {.ggOceanMapsenv <- new.env(); .ggOceanMapsenv$datapath
## <- 'YourCustomPath'}. You can use usethis::edit_r_profile() to edit the
## file. '~/ggOceanMapsLargeData' would make it in a writable folder on
## most operating systems.
## 
## Attaching package: 'ggOceanMaps'
## The following object is masked from 'package:plyr':
## 
##     round_any
## The following object is masked from 'package:cowplot':
## 
##     theme_map
## Warning: Removed 1 row containing missing values or values outside the scale range
## (`geom_point()`).

## Summarize Vessel Activity – Open Ended

#’ This next section is open-ended. In a short paragraph (either commented here or in a separate #’ document), explain the activity of the vessel whose tracks you plotted in the previous section.
#’ Use the space below to show how you generated any summary statistics (e.x., voyage length, #’ fishing hours) you use in your description.

The vessel (mmsi - 224892000) left port from Peru North of Lima on 6/2/2017 0:08 (shortly after midnight). The vessel traveled to ~ -22º S and appeared to trawl North and South. A quick glimpse at the bathymetry of the area shows that the area is relatively the same depth. But this area is in the middle of the Peru/ Humboldt Current coming from the West that brings in cool, low salinity water. It is likely that this vessel is targeting a small species of fish such as anchovies, sardines or mackerel.

The vessel then went more inshore and fished in a similar North - South method closer the the EEZ before again heading West again. The vessel fished in the same area as it started, then returned to port.