Type: Package
Title: Plot Data on Oceanographic Maps using 'ggplot2'
Version: 2.2.0
Date: 2024-01-15
URL: https://mikkovihtakari.github.io/ggOceanMaps/
BugReports: https://github.com/MikkoVihtakari/ggOceanMaps/issues
Description: Allows plotting data on bathymetric maps using 'ggplot2'. Plotting oceanographic spatial data is made as simple as feasible, but also flexible for custom modifications. Data that contain geographic information from anywhere around the globe can be plotted on maps generated by the basemap() or qmap() functions using 'ggplot2' layers separated by the '+' operator. The package uses spatial shape- ('sf') and raster ('stars') files, geospatial packages for R to manipulate, and the 'ggplot2' package to plot these files. The package ships with low-resolution spatial data files and higher resolution files for detailed maps are stored in the 'ggOceanMapsLargeData' repository on GitHub and downloaded automatically when needed.
Depends: R (≥ 3.5.0), ggplot2
Imports: sf, stars, methods, utils, smoothr, units
Suggests: ggspatial, cowplot, knitr, rmarkdown, scales, ggnewscale
License: GPL-3
Encoding: UTF-8
RoxygenNote: 7.2.3
LazyData: true
LazyDataCompression: xz
NeedsCompilation: no
Packaged: 2024-01-15 10:56:44 UTC; a22357
Author: Mikko Vihtakari ORCID iD [aut, cre] (affiliation: Institute of Marine Research), Roger Bivand [ctb], Hadley Wickham [ctb]
Maintainer: Mikko Vihtakari <mikko.vihtakari@hi.no>
Repository: CRAN
Date/Publication: 2024-01-15 13:10:05 UTC

Plot Data on Oceanographic Maps using ggplot2

Description

Uses ggplot2 syntax and shape files to plot research data on oceanographic maps anywhere around the globe.

Details

The general map-making function for ggOceanMaps is basemap. This function creates a "canvas" on which research data can be plotted. The basemap function is analogous to ggplot function from the ggplot2 package. Remember to use data = <<NAMEOFDATASET>> for additional geometries you plot on basemaps (basemap(60) + geom_point(data = data.frame(lon = 50, lat = 70), aes(x = lon, y = lat)) as an example). As a shortcut, you may also use qmap(data.frame(lon = c(10, 50), lat = c(60, 70))). Bathymetry is plotted using the bathymetry argument.

Author(s)

Maintainer: Mikko Vihtakari mikko.vihtakari@hi.no (ORCID) (Institute of Marine Research)

Other contributors:

See Also

Useful links:


Convert font sizes measured as points to ggplot font sizes

Description

Converts font sizes measured as points (as given by most programs such as MS Word etc.) to ggplot font sizes

Usage

FS(x)

Arguments

x

numeric vector giving the font sizes in points

Value

Returns a numeric vector of lenght x of ggplot font sizes

See Also

Other size adjustors: LS()


Convert line sizes measured as points to ggplot line sizes

Description

Converts line sizes measured as points (as given by most programs such as Adobe Illustrator etc.) to ggplot font sizes

Usage

LS(x)

Arguments

x

numeric vector giving the lines sizes in points

Value

Returns a numeric vector of lenght x of ggplot line sizes

See Also

Other size adjustors: FS()


Automatic limits for basemap

Description

Find limits for a basemap from a data frame.

Usage

auto_limits(
  data,
  lon = NULL,
  lat = NULL,
  proj.in = 4326,
  proj.out = NULL,
  expand.factor = NULL,
  verbose = FALSE
)

Arguments

data

Data frame or a spatial object containing data for which the limits should be calculated.

lon, lat

Names of longitude and latitude columns in data as character or integer index. If NULL, the column names are guessed.

proj.in

Original CRS projection. Must be defined as character argument.

proj.out

Resulting map projection. See transform_coord.

expand.factor

Expansion factor for map limits. Set to NULL to ignore.

verbose

Logical indicating whether information about the projection and guessed column names should be returned as message. Set to FALSE to make the function silent.

Details

This is an internal function, which is automatically run by the basemap function.

Value

A list of limits and projections in proj.in and proj.out formats.

Author(s)

Mikko Vihtakari

See Also

Other customize shapefiles: reorder_layers(), theme_map()

Examples

auto_limits(data = expand.grid(lon = c(-120, 180, 120),
   lat = c(60, 60, 80)))

Create a ggplot2 basemap for plotting variables

Description

Creates a ggplot2 basemap for further plotting of data.

Usage

basemap(
  x = NULL,
  limits = NULL,
  data = NULL,
  shapefiles = NULL,
  crs = NULL,
  bathymetry = FALSE,
  glaciers = FALSE,
  rotate = FALSE,
  legends = TRUE,
  legend.position = "right",
  lon.interval = NULL,
  lat.interval = NULL,
  bathy.style = NULL,
  downsample = 0,
  bathy.border.col = NA,
  bathy.size = 0.1,
  bathy.alpha = 1,
  land.col = "grey60",
  land.border.col = "black",
  land.size = 0.1,
  gla.col = "grey95",
  gla.border.col = "black",
  gla.size = 0.1,
  grid.col = "grey70",
  grid.size = 0.1,
  base_size = 11,
  projection.grid = FALSE,
  expand.factor = 1,
  verbose = FALSE
)

Arguments

x

The limit type (limits, data, or shapefiles) is automatically recognized from the class of this argument.

limits

Map limits. One of the following:

  • numeric vector of length 4: The first element defines the start longitude, the second element the end longitude (counter-clockwise), the third element the minimum latitude, and the fourth element the maximum latitude of the bounding box. Also accepts sf::st_bbox type named vectors with limits in any order. The coordinates can be given as decimal degrees or coordinate units for shapefiles used by a projected map. Produces a rectangular map. Latitude limits not given in min-max order are automatically ordered to respect this requirement.

  • single integer between 30 and 88 or -88 and -30 produces a polar map for the Arctic or Antarctic, respectively.

Can be omitted if data or shapefiles are defined.

data

A data frame, sp, or sf shape containing longitude and latitude coordinates. If a data frame, the coordinates have to be given in decimal degrees. The limits are extracted from these coordinates and produce a rectangular map. Suited for situations where a certain dataset is plotted on a map. The function attempts to guess the correct columns and it is advised to use intuitive column names for longitude (such as "lon", "long", or "longitude") and latitude ("lat", "latitude") columns. Can be omitted if limits or shapefiles are defined.

shapefiles

Either a list containing shapefile information or a character argument referring to a name of pre-made shapefiles in shapefile_list. This name is partially matched. Can be omitted if limits or data is defined as decimal degrees.

crs

Coordinate reference system (CRS) for the map. If NULL (default), the CRS is selected automatically based on limits, data, or shapefiles. Passed to st_crs. Typically integers giving the EPGS code are the easiest. Cannot be used simultaneously with rotate.

bathymetry

Logical indicating whether bathymetry should be added to the map. Functions together with bathy.style. See Details.

glaciers

Logical indicating whether glaciers and ice sheets should be added to the map.

rotate

Logical indicating whether the projected maps should be rotated to point towards the pole relative to the mid-longitude limit.

legends

Logical indicating whether the legend for bathymetry should be shown.

legend.position

The position for ggplot2 legend. See the argument with the same name in theme.

lon.interval, lat.interval

Numeric value specifying the interval of longitude and latitude grids. NULL finds reasonable defaults depending on limits.

bathy.style

Character (plots bathymetry; list of alternatives in Details) or NULL ("raster_binned_blues" if bathymetry = TRUE) defining the bathymetry style. Partially matched, can be abbreviated, and used to control bathymetry plotting together with bathymetry. See Details.

downsample

Integer defining the downsampling rate for raster bathymetries. A value of 0 (default) does not downsample, 1 skips every second row, 2 every second and third. See geom_stars

bathy.alpha

Transparency parameter for the bathymetry fill color. See scale_alpha.

land.col, gla.col, grid.col

Character code specifying the color of land, glaciers, and grid lines, respectively. Use NA to remove the grid lines.

land.border.col, gla.border.col, bathy.border.col

Character code specifying the color of the border line for land, glacier, and bathymetry shapes.

land.size, gla.size, bathy.size, grid.size

Numeric value specifying the width of the border line land, glacier and bathymetry shapes as well as the grid lines, respectively. Use the LS function for a specific width in pt. See Details.

base_size

Base size parameter for ggplot. See ggtheme.

projection.grid

Logical indicating whether the coordinate grid should show projected coordinates instead of decimal degree values. Useful to define limits for large maps in polar regions.

expand.factor

Expansion factor for map limits. Can be used to zoom in (decrease the value under 1) and out (increase the value over 1) automatically (data) limited maps. Defaults to 1, which means that outermost data points are located at the boundaries of the plotting region.

verbose

Logical indicating whether information about the projection and guessed column names should be returned as messages. Set to FALSE to make the function silent.

Details

The function uses ggplot2, sf, stars and spatial files to plot maps of the world's oceans.

Limits

If the limits are in decimal degrees, the longitude limits ([1:2]) specify the start and end segments of corresponding angular lines that should reside inside the map area. The longitude limits are defined counter-clockwise. The latitude limits [3:4] define the parallels that should reside inside the limited region given the longitude segments. Note that the actual limited region becomes wider than the polygon defined by the coordinates (shown in Examples). Using data to limit the map, making the points barely fit into the map. The expand.factor argument can be used to adjust the space between map borders and points. If the limits are given as projected coordinates or as decimal degrees for maps with -60 < latitude < 60, limit elements represent lines encompassing the map area in cartesian space.

Projections

If the shapefiles are not specified, the function uses either the limits or data arguments to decide which projection to use. Up-to-date conditions are defined in define_shapefiles and shapefile_list functions. At the time of writing, the function uses three different projections (given as EPSG codes)

The rotate argument changes the pre-defined projection such that mid-longitude point in the map points northward.

The crs argument can be used to define the projection, which can be useful when plotting, for instance, model data that are difficult to transform into another projection.

Bathymetry

Bathymetry can be plotted by simply specifying bathymetry = TRUE or bathy.style (you won't need to specify both any longer). The former uses a low-resolution raster file shipped with ggOceanMaps. The package contains an option to plot higher resolution bathymetries than the default binned blue alternative (bathy.style = "raster_binned_blues"). These bathymetries can be accessed by specifying the bathy.style argument and require a download from ggOceanMapsLargeData or other online repositories. The bathy.style character argument consists of three parts separated by a _. The first part gives the type: raster, poly(gon), or contour. The two latter ones use vector data. The second part gives the resolution: binned, continuous or user. The continuous and user options cannot be used for vector data. The user option accepts any raster file that can be opened using read_stars. The path to the file has to be stored in ggOceanMaps.userpath option (e.g. options(ggOceanMaps.userpath = "PATH_TO_THE_FILE")) (you can set this in .Rprofile to avoid having to type it every time). The last part defines the color: blues or grays. These options can be abbreviated by specifying the first letter of each part. Gray contour lines are an exception to the rule above and can be plotted using bathy.style = "contour_gray". Future versions may contain a combination of raster and gray contours, but these have not been implemented yet. Currently implemented bathy.style alternatives are:

The default can be changed by setting the ggOceanMaps.bathy.style option. options(ggOceanMaps.bathy.style = "poly_blues") would make the style similar to older pre-2.0 versions of ggOceanMaps.

Pre-made shapefiles

If the limits are not defined as decimal degrees (any longitude outside the range [-180, 180] or latitude [-90, 90]), the function will ask to specify shapefiles. The shapefiles can be defined by partially matching the names of the pre-made shapefiles in shapefile_list (e.g. "Ar" would be enough for "ArcticStereographic") or by specifying custom shapefiles.

Custom shapefiles

Custom shapefiles have to be a named list containing at least the following elements:

See Examples.

Line width and font size

The line size aesthetics in ggplot2 generates approximately 2.13 wider lines measured in pt than the given values. If you want a specific line width in pt, use the internal function LS to convert the desired line width to the ggplot2 equivalent. A similar function is also available for font sizes (FS).

Value

Returns a ggplot map, which can be assigned to an object and modified as any ggplot object.

Author(s)

Mikko Vihtakari

References

Note that if you use this function to generate maps for a publication, it is advised to cite the underlying data. The spatial data used by this function have been acquired from the following sources:

See Also

ggplot

Other basemap functions: qmap(), shapefile_list(), transform_coord()

Examples

# The easiest way to produce a map is to use the limits
# argument and decimal degrees:

basemap(limits = 60) # synonym to basemap(60)

# Bathymetry can be added using the respective argument:
basemap(limits = -60, bathymetry = TRUE)

## Not run: 
# Glaciers require a download in the new version:
basemap(limits = -60, glaciers = TRUE, shapefiles = "Arctic")

## End(Not run)

# The easiest way to add data on the maps is to use the ggspatial functions:
dt <- data.frame(lon = c(-150, 150), lat = c(60, 90))
if(requireNamespace("ggspatial", quietly = TRUE)) {
basemap(data = dt, bathymetry = TRUE) +
  ggspatial::geom_spatial_point(data = dt, aes(x = lon, y = lat), 
    color = "red")
}
## Not run: 
# Note that writing out data = dt is required because there are multiple
# underlying ggplot layers plotted already:
basemap(data = dt) +
ggspatial::geom_spatial_point(dt, aes(x = lon, y = lat), color = "red")
#> Error: `mapping` must be created by `aes()`

## End(Not run)

# If you want to use native ggplot commands, you need to transform your data
# to the projection used by the map:
dt <- transform_coord(dt, bind = TRUE)

basemap(data = dt) + 
  geom_point(data = dt, aes(x = lon.proj, y = lat.proj), color = "red")

# The limits argument of length 4 plots a map anywhere in the world:
basemap(limits = c(100, 160, -20, 30), bathymetry = TRUE)

# The limits are further expanded when using the data argument:

dt <- data.frame(lon = c(-160, 160, 160, -160), lat = c(80, 80, 60, 60))

if(requireNamespace("ggspatial", quietly = TRUE)) {
basemap(data = dt) +
  ggspatial::geom_spatial_polygon(data = dt, aes(x = lon, y = lat),
    fill = NA, color = "red")

# Rotate:
basemap(data = dt, rotate = TRUE) +
  ggspatial::geom_spatial_polygon(data = dt, aes(x = lon, y = lat),
    fill = NA, color = "red")
}

# Alternative:
basemap(data = dt, rotate = TRUE) +
  geom_polygon(data = transform_coord(dt, rotate = TRUE), 
    aes(x = lon, y = lat), fill = NA, color = "red")

## To find UTM coordinates to limit a polar map:
basemap(limits = 60, projection.grid = TRUE)

## Not run: 
# (Arctic shapes require a download in 2.0)
basemap(limits = c(2.5e4, -2.5e6, 2e6, -2.5e5), shapefiles = "Arctic")

# Using custom shapefiles (requires download):
data(bs_shapes, package = "ggOceanMapsData")
basemap(shapefiles = list(land = bs_land))#' 

# Premade shapefiles from ggOceanMapsLargeData (requires download):
basemap("BarentsSea", bathymetry = TRUE)

## End(Not run)

# grid.col = NA removes grid lines, rotate = TRUE rotates northwards: 
basemap(limits = c(-180, -140, 50, 70), grid.col = NA, rotate = TRUE)

# Rename axis labels

basemap(limits = c(-140, -105, 20, 40), bathymetry = TRUE) + xlab("Lat")

# Remove axis labels

basemap(limits = c(0, 60, 68, 80)) + labs(x = NULL, y = NULL)

basemap(limits = c(0, 60, 68, 80), rotate = TRUE) +
theme(axis.title = element_blank(),
      axis.text = element_blank(),
      axis.ticks.x = element_blank(),
      axis.ticks.y = element_blank()
      )


Create basemapData object for basemap plotting

Description

Internal function to create a basemapData object for basemap

Usage

basemap_data(
  limits = NULL,
  data = NULL,
  shapefiles = NULL,
  crs = NULL,
  bathymetry = FALSE,
  bathy.type = NULL,
  downsample = 0,
  glaciers = FALSE,
  lon.interval = NULL,
  lat.interval = NULL,
  expand.factor = 1.1,
  rotate = FALSE,
  verbose = FALSE
)

Arguments

limits

Map limits. One of the following:

  • numeric vector of length 4: The first element defines the start longitude, the second element the end longitude (counter-clockwise), the third element the minimum latitude, and the fourth element the maximum latitude of the bounding box. Also accepts sf::st_bbox type named vectors with limits in any order. The coordinates can be given as decimal degrees or coordinate units for shapefiles used by a projected map. Produces a rectangular map. Latitude limits not given in min-max order are automatically ordered to respect this requirement.

  • single integer between 30 and 88 or -88 and -30 produces a polar map for the Arctic or Antarctic, respectively.

Can be omitted if data or shapefiles are defined.

data

A data frame, sp, or sf shape containing longitude and latitude coordinates. If a data frame, the coordinates have to be given in decimal degrees. The limits are extracted from these coordinates and produce a rectangular map. Suited for situations where a certain dataset is plotted on a map. The function attempts to guess the correct columns and it is advised to use intuitive column names for longitude (such as "lon", "long", or "longitude") and latitude ("lat", "latitude") columns. Can be omitted if limits or shapefiles are defined.

shapefiles

Either a list containing shapefile information or a character argument referring to a name of pre-made shapefiles in shapefile_list. This name is partially matched. Can be omitted if limits or data is defined as decimal degrees.

crs

Coordinate reference system (CRS) for the map. If NULL (default), the CRS is selected automatically based on limits, data, or shapefiles. Passed to st_crs. Typically integers giving the EPGS code are the easiest. Cannot be used simultaneously with rotate.

bathymetry

Logical indicating whether bathymetry should be added to the map. Functions together with bathy.style. See Details.

downsample

Integer defining the downsampling rate for raster bathymetries. A value of 0 (default) does not downsample, 1 skips every second row, 2 every second and third. See geom_stars

glaciers

Logical indicating whether glaciers and ice sheets should be added to the map.

lon.interval, lat.interval

Numeric value specifying the interval of longitude and latitude grids. NULL finds reasonable defaults depending on limits.

expand.factor

Expansion factor for map limits. Can be used to zoom in (decrease the value under 1) and out (increase the value over 1) automatically (data) limited maps. Defaults to 1, which means that outermost data points are located at the boundaries of the plotting region.

rotate

Logical indicating whether the projected maps should be rotated to point towards the pole relative to the mid-longitude limit.

verbose

Logical indicating whether information about the projection and guessed column names should be returned as messages. Set to FALSE to make the function silent.

Details

This is an internal function, which is automatically run by the basemap function. Common users do not need to worry about these details.

Value

A list of class basemapData containing information required for plotting a basemap.

Author(s)

Mikko Vihtakari

See Also

basemap


Clip a shapefile using a bounding area

Description

Clips an area from a larger shapefile provided in sf or sp formats.

Usage

clip_shapefile(
  x,
  limits,
  proj.limits = 4326,
  simplify = FALSE,
  tol = 60,
  return.boundary = FALSE,
  extra.validate = FALSE
)

Arguments

x

Original shapefile to be clipped as a an sf or sp polygons object. Required. Must contain CRS information.

limits

The constraining area used to clip x. Required. Either a numeric vector of length 4 or a spatial object from the sf or sp packages. The first element of the numeric vector defines the minimum longitude, second element the maximum longitude, third element the minimum latitude and fourth element the maximum latitude of the bounding box. If a spatial object, it must contain CRS information. See details.

proj.limits

The CRS projection attributes for limits. Hence format accepted by st_crs will suffice but integers are the easiest. Defaults to decimal degrees.

simplify

Should the x geometry be simplified before clipping? Useful to make the function faster for large shape files. Uses st_simplify function.

tol

Numerical tolerance value to be used for simplification. See ?sf::st_simplfy.

return.boundary

Logical. If TRUE returns the clip boundary together with the shapefile.

extra.validate

Logical indicating whether x should be run through extra validation. Slows down the function but is necessary in some cases involving anti-meridian.

Details

The function uses the st_intersection function to clip smaller polygons from larger ones. The clip area is constrained by either a numeric vector or a spatial object in the limits argument. Defining limits by a sf object gives greater freedom for the clip area as the area does not have to be rectangular.

Value

Clipped spatial object. If return.boundary = TRUE, a list containing the shapefile together with the clip boundary.

Author(s)

Mikko Vihtakari

See Also

Other create shapefiles: geonorge_bathymetry(), raster_bathymetry(), vector_bathymetry()


Create clip boundary from decimal degree limits

Description

Creates a clip boundary for map cropping from decimal degree limits counter-clockwise following parallels

Usage

dd_clip_boundary(limits, crs, expand.factor = NULL)

Arguments

limits

Numeric vector of length 4 giving the map limits in decimal degrees. See basemap.

crs

Coordinate reference system in st_crs format.

expand.factor

Expansion factor for map limits. Set to NULL to ignore.

Author(s)

Mikko Vihtakari


Decimal degree land shapes

Description

Decimal degree land shapes

Usage

dd_land

Format

Simple feature collection land shapes in decimal degrees (EPSG:4326). Obtained from Natural Earth Data (10m vectors). Includes the islands dataset.

Source

Natural Earth Data

See Also

Other mapfiles: dd_rbathy


Decimal degree bathymetry

Description

Decimal degree bathymetry

Usage

dd_rbathy

Format

Raster bathymetry in decimal degrees (EPSG:4326). Downsampled from ETOPO 60 arc-second grid.

Source

NOAA National Centers for Environmental Information. 2022: ETOPO 2022 15 Arc-Second Global Relief Model. NOAA National Centers for Environmental Information. doi:10.25921/fd45-gt74

See Also

Other mapfiles: dd_land


Convert decimal degree values to angular degrees

Description

Converts decimal degree values to angular degrees. Used in decimal degree limit calculations.

Usage

dd_to_deg(x)

Arguments

x

numeric to be converted

Value

A vector of angular degrees

Author(s)

Mikko Vihtakari

See Also

Other degree converters: deg_to_dd()


Define bathymetry style for basemap

Description

Defines bathymetry style to be used in basemap

Usage

define_bathy_style(x)

Arguments

x

Character argument giving the input bathymetry style. Partially matched and can be abbreviated. See bathy.style in basemap.

Value

Returns a named character vector with the name pointing to the bathymetry style and value to internal map element command for basemap (see map_cmd).

Author(s)

Mikko Vihtakari


Define a shapefile to use in plotting from the limits argument

Description

An internal function to make basemap code more readable

Usage

define_shapefiles(limits, force_dd = FALSE)

Arguments

limits

A numeric vector of length 4: The first element defines the minimum longitude, the second element the maximum longitude, the third element the minimum latitude and the fourth element the maximum latitude of the bounding box.

force_dd

Logical indicating whether the shapefile should be forced to DecimalDegree. Required for transforming dd_* shapefile objects to other projections.

Details

This is an internal function, which is automatically run by the basemap function.

Value

A list containing the correct shapefile, a logical statement whether the limits were supplied as decimal degrees and coordinate reference system.

Author(s)

Mikko Vihtakari

See Also

basemap


Convert angular degrees to decimal degree values

Description

Converts angular degree values to decimal degrees. Used in decimal degree limit calculations.

Usage

deg_to_dd(x)

Arguments

x

numeric to be converted

Value

A vector of decimal degrees

Author(s)

Mikko Vihtakari

See Also

Other degree converters: dd_to_deg()


Calculate distance to the closest land for coordinates

Description

Calculates the closest distance to land for coordinates in a data frame

Usage

dist2land(
  data,
  lon = NULL,
  lat = NULL,
  shapefile = "DecimalDegree",
  proj.in = 4326,
  bind = TRUE,
  dist.col = "ldist",
  binary = FALSE,
  verbose = TRUE
)

Arguments

data

Data frame or sf object containing geographic coordinates.

lon, lat

Either the names of the longitude and latitude columns in data or NULL to guess the longitude and/or latitude columns in data.

shapefile

Land shape to which distances should be calculated. Either a character argument referring to a name of pre-made shapefiles in shapefile_list, a single sf or sp polygons object object or NULL to enable automatic definition of the land shapes based on data. Set to "DecimalDegree" by default which enables great circle distances using s2 features assuming a spherical Earth (as a contrast to earlier versions of the function which used flat Earth).

proj.in

coordinate reference system of data.

bind

Logical indicating whether x should be returned with the distances (TRUE, default) or should the distances be returned as vector (FALSE).

dist.col

The name of the distance column, if bind = TRUE. Defaults to "ldist".

binary

Logical indicating whether binary (TRUE = the position is in the ocean, FALSE = the position is on land) should be returned instead of distances. Speeds up the function considerably.

verbose

Logical indicating whether information about the process should be returned as messages. Set to FALSE to make the function silent.

Details

The function calculates great circle spherical distances using the st_distance function by default. The function can be slow for large datasets. If you only want to use the function to remove (wrong) observations reported on land, set the binary argument to TRUE. This speeds up the calculations by a factor of ten.

Value

Returns a vector if bind = FALSE, otherwise a data frame. The distances are given in a new column defined by the dist.col argument. The distances are kilometers if binary = FALSE, otherwise logical (TRUE = the position is in the ocean, FALSE = the position is on land).

Author(s)

Mikko Vihtakari

Examples

# Simple example:
dt <- data.frame(lon = seq(-20, 80, length.out = 41), lat = 50:90)
dt <- dist2land(dt, verbose = FALSE)

qmap(dt, color = ldist) + scale_color_viridis_c()

# Datasets covering the entire Earth seem to work now, except 0,0 lon/lat point
lon = deg_to_dd(seq(0,360,30)); lat = c(80,50,20,0,-20,-50,-80)

dt <- data.frame(
 lon = rep(lon, length(lat)), lat = rep(lat, each = length(lon)))

qmap(dist2land(dt, verbose = FALSE), color = ldist) +
 scale_color_viridis_c()

## Not run: 
dt <- data.frame(
  lon = deg_to_dd(seq(0,360,length.out = 1e3)), 
  lat = rep(60, 1000))
  
# The distance calculation is slow for large datasets
system.time(dist2land(dt))
# user  system elapsed 
# 12.677   0.146  12.849 

# binary = TRUE speeds the function up
system.time(dist2land(dt, binary = TRUE))
# user  system elapsed 
# 1.239   0.120   1.369 

## End(Not run)

Major fisheries areas (hovedomraade) of Norway

Description

Major fisheries areas (hovedomraade) of Norway

Usage

fdir_main_areas

Format

sf object containing major fishing zones defined by the Norwegian Directorate of Fisheries. Contains also Northwest Atlantic Fisheries Organization's divisions where Norwegian vessels tend to fish.

Source

Norwegian Directorate of Fisheries and Northwest Atlantic Fisheries Organization

See Also

Other datasets: fdir_sub_areas, ices_areas

Examples

if(requireNamespace("ggspatial")) {
 
basemap(fdir_main_areas) + 
ggspatial::annotation_spatial(fdir_main_areas, fill = NA)

}

Norwegian sub-areas (lokasjon) for commercial fishing

Description

Norwegian sub-areas (lokasjon) for commercial fishing

Usage

fdir_sub_areas

Format

sf object containing major fishing zones defined by the Norwegian Directorate of Fisheries.

Source

Norwegian Directorate of Fisheries

See Also

Other datasets: fdir_main_areas, ices_areas

Examples

if(requireNamespace("ggspatial")) {

basemap(fdir_sub_areas) + 
ggspatial::annotation_spatial(fdir_sub_areas, fill = NA)

}

Open Geonorge bathymetry shapefiles

Description

Opens and formats Geonorge bathymetry shapefiles ready for plotting in ggOceanMaps

Usage

geonorge_bathymetry(filepath, layer = NULL, verbose = FALSE)

Arguments

filepath

Character string defining the path to the .gml file. Must contain the file extension.

layer

Character string defining the layer containing depth information. If NULL assumed to be "dybdeareal".

verbose

Logical indicating whether information the reading process should be returned.

Details

You can download the bathymetry polygon shapefiles from Geonorge. Download the file in GLM format.

Value

An sf object containing the depth polygons. Uses same projection than bathy (see CRS).

Author(s)

Mikko Vihtakari

See Also

Other create shapefiles: clip_shapefile(), raster_bathymetry(), vector_bathymetry()


Extract depth for coordinates from a raster bathymetry dataset

Description

Extracts depth from basemap bathymetry raster dataset for coordinates in a data frame

Usage

get_depth(
  data,
  bathy.style = "raster_continuous",
  lon = NULL,
  lat = NULL,
  shapefile = "DecimalDegree",
  proj.in = 4326,
  bind = TRUE,
  depth.col = "depth",
  verbose = FALSE
)

Arguments

data

Data frame or sf object containing geographic coordinates.

bathy.style

Character defining the basemap bathymetry raster which should be used for the depth extraction. Valid alternatives: "raster_binned" (or "rb"), "raster_continuous" (or "rc"; default), or "raster_user" (or "ru").

lon, lat

Either the names of the longitude and latitude columns in data or NULL to guess the longitude and/or latitude columns in data.

shapefile

Land shape to which distances should be calculated. Either a character argument referring to a name of pre-made shapefiles in shapefile_list, a single sf or sp polygons object object or NULL to enable automatic definition of the land shapes based on data. Set to "DecimalDegree" by default which enables great circle distances using s2 features assuming a spherical Earth (as a contrast to earlier versions of the function which used flat Earth).

proj.in

coordinate reference system of data.

bind

Logical indicating whether x should be returned with the distances (TRUE, default) or should the distances be returned as vector (FALSE).

depth.col

The name of the depth column, if bind = TRUE. Defaults to "depth".

verbose

Logical indicating whether information about the process should be returned as messages. Set to FALSE to make the function silent.

Details

Uses the st_extract function to extract values from basemap bathymetry raster grids. Does not work for vector bathymetries.

Value

Returns a vector if bind = FALSE, otherwise a data frame. The depths are given in a new column defined by the dist.col argument. The distances are kilometers. NA distance means that the position is on land.

Author(s)

Mikko Vihtakari

Examples

## Not run: 
dt <- data.frame(lon = seq(-20, 80, length.out = 41), lat = 50:90)
dt <- get_depth(dt)
qmap(dt, color = depth) + scale_color_viridis_c()

## End(Not run)

Guess longitude and latitude columns in a data frame

Description

An internal function to make basemap code more readable

Usage

guess_coordinate_columns(data, lon = NULL, lat = NULL)

Arguments

data

Dataframe containing data for which the limits should be calculated.

lon, lat

Character defining the name of the longitude and latitude columns in data. Use NULL to guess the longitude and/or latitude columns in x.

Details

This is an internal function, which is automatically run by the basemap function.

Value

A named vector of colummn names.

Author(s)

Mikko Vihtakari

See Also

auto_limits, transform_coord, basemap


ICES Advisory Areas

Description

ICES Advisory Areas

Usage

ices_areas

Format

sf object containing ICES Advisory Areas.

Source

International Council for the Exploration of the Sea

See Also

Other datasets: fdir_main_areas, fdir_sub_areas

Examples

if(requireNamespace("ggspatial")) {

basemap(ices_areas) + 
ggspatial::annotation_spatial(ices_areas, fill = NA)

}

Test whether a limit argument is specified as decimal degrees.

Description

An internal function to make basemap code more readable

Usage

is_decimal_limit(limits)

Arguments

limits

A numeric vector of length 1 or 4. See basemap

Details

This is an internal function, which is automatically run by the basemap function.

Value

A logical value

Author(s)

Mikko Vihtakari

See Also

basemap


Load large shapefile objects

Description

Internal function to load large shapefile objects. Downloads the files if they are not found getOption("ggOceanMaps.datapath")

Usage

load_map_data(x, force = FALSE, downsample = 0)

Arguments

x

An object from shapefile_list.

force

Logical indicating whether to download the file even though it exists. Useful when files in the Github repository have been changed. Overwrites the old file.

downsample

Integer defining the downsampling rate for raster bathymetries. A value of 0 (default) does not downsample, 1 skips every second row, 2 every second and third. See geom_stars

Details

This is an internal function, which is automatically run by the basemap function. Common users do not need to worry about these details.

Value

A list of spatial objects

Author(s)

Mikko Vihtakari

See Also

basemap


Return map elements for basemap

Description

An internal function to make basemap code more readable

Usage

map_cmd(command, alternative = FALSE)

Arguments

command

basemap layer to be added

alternative

logical to return alternative formmatting in certain cases. Used to reduce if-else statements in basemap.

Details

This is an internal function, which is automatically run by the basemap function. Common users do not need to worry about these details. Basemap elements can added together using this function, parse and eval.

Value

A character string containing a ggplot2 plotting command. Use eval(parse(text=...)) to plot the string.

Author(s)

Mikko Vihtakari

See Also

basemap

Examples

## An example for utm map without glaciers or bathymetry
## Not run: eval(parse(text=paste(map_cmd("base"), map_cmd("land_utm"),
map_cmd("grid_utm"), map_cmd("defs_utm"), sep = "+")))
## End(Not run)

Quick map

Description

qmap is a shortcut similar to ggplot2's qplot designed to quickly plot data with a limited range of options.

Usage

qmap(
  data,
  ...,
  x = NULL,
  y = NULL,
  geom = "point",
  limits = NULL,
  shapefiles = NULL,
  crs = NULL,
  bathymetry = FALSE,
  glaciers = FALSE,
  rotate = FALSE,
  legends = TRUE,
  legend.position = "right",
  lon.interval = NULL,
  lat.interval = NULL,
  bathy.style = NULL,
  downsample = 0,
  bathy.border.col = NA,
  bathy.size = 0.1,
  bathy.alpha = 1,
  land.col = "grey60",
  land.border.col = "black",
  land.size = 0.1,
  gla.col = "grey95",
  gla.border.col = "black",
  gla.size = 0.1,
  grid.col = "grey70",
  grid.size = 0.1,
  base_size = 11,
  projection.grid = FALSE,
  expand.factor = 1.1,
  verbose = FALSE
)

Arguments

data

Data frame to use.

x, y, ...

Aesthetics passed into each layer. Longitude and latitude columns are automatically recognized using the guess_coordinate_columns function.

geom

Character argument specifying geom(s) to draw. Defaults to "point". Other alternatives are "text" and "label". The "text" option can also be triggered by simply mapping a variable to label (see Examples).

limits

Map limits. One of the following:

  • numeric vector of length 4: The first element defines the start longitude, the second element the end longitude (counter-clockwise), the third element the minimum latitude, and the fourth element the maximum latitude of the bounding box. Also accepts sf::st_bbox type named vectors with limits in any order. The coordinates can be given as decimal degrees or coordinate units for shapefiles used by a projected map. Produces a rectangular map. Latitude limits not given in min-max order are automatically ordered to respect this requirement.

  • single integer between 30 and 88 or -88 and -30 produces a polar map for the Arctic or Antarctic, respectively.

Can be omitted if data or shapefiles are defined.

shapefiles

Either a list containing shapefile information or a character argument referring to a name of pre-made shapefiles in shapefile_list. This name is partially matched. Can be omitted if limits or data is defined as decimal degrees.

crs

Coordinate reference system (CRS) for the map. If NULL (default), the CRS is selected automatically based on limits, data, or shapefiles. Passed to st_crs. Typically integers giving the EPGS code are the easiest. Cannot be used simultaneously with rotate.

bathymetry

Logical indicating whether bathymetry should be added to the map. Functions together with bathy.style. See Details.

glaciers

Logical indicating whether glaciers and ice sheets should be added to the map.

rotate

Logical indicating whether the projected maps should be rotated to point towards the pole relative to the mid-longitude limit.

legends

Logical indicating whether the legend for bathymetry should be shown.

legend.position

The position for ggplot2 legend. See the argument with the same name in theme.

lon.interval, lat.interval

Numeric value specifying the interval of longitude and latitude grids. NULL finds reasonable defaults depending on limits.

bathy.style

Character (plots bathymetry; list of alternatives in Details) or NULL ("raster_binned_blues" if bathymetry = TRUE) defining the bathymetry style. Partially matched, can be abbreviated, and used to control bathymetry plotting together with bathymetry. See Details.

downsample

Integer defining the downsampling rate for raster bathymetries. A value of 0 (default) does not downsample, 1 skips every second row, 2 every second and third. See geom_stars

bathy.alpha

Transparency parameter for the bathymetry fill color. See scale_alpha.

land.col, gla.col, grid.col

Character code specifying the color of land, glaciers, and grid lines, respectively. Use NA to remove the grid lines.

land.border.col, gla.border.col, bathy.border.col

Character code specifying the color of the border line for land, glacier, and bathymetry shapes.

land.size, gla.size, bathy.size, grid.size

Numeric value specifying the width of the border line land, glacier and bathymetry shapes as well as the grid lines, respectively. Use the LS function for a specific width in pt. See Details.

base_size

Base size parameter for ggplot. See ggtheme.

projection.grid

Logical indicating whether the coordinate grid should show projected coordinates instead of decimal degree values. Useful to define limits for large maps in polar regions.

expand.factor

Expansion factor for map limits. Can be used to zoom in (decrease the value under 1) and out (increase the value over 1) automatically (data) limited maps. Defaults to 1, which means that outermost data points are located at the boundaries of the plotting region.

verbose

Logical indicating whether information about the projection and guessed column names should be returned as messages. Set to FALSE to make the function silent.

Value

Returns a ggplot map, which can be assigned to an object and modified as any ggplot object.

Author(s)

Mikko Vihtakari

See Also

Other basemap functions: basemap(), shapefile_list(), transform_coord()

Examples

dt <- data.frame(lon = c(-100, -80, -60), lat = c(10, 25, 40), var = c("a", "a", "b"))

# Quickly see position of data
qmap(dt)


# Set color
qmap(dt, color = I("blue")) 

# Map color to a variable
qmap(dt, color = var) 
 
# Map text to a variable 
qmap(dt, label = var) 

# All basemap arguments work in qmap()
dt <- data.frame(lon = c(-80, -80, -50, -50), lat = c(65, 80, 80, 65))
qmap(dt, rotate = TRUE)


Return function output quietly

Description

Returns function output without printed cat messages

Usage

quiet(x)

Arguments

x

function

Value

Output of x

Author(s)

Hadley Wickham


Simplify a bathymetry raster ready for vectorization

Description

Simplifies bathymetry raster ready for the vector_bathymetry function. Warning: processing may take a long time if the bathymetry raster is large.

Usage

raster_bathymetry(
  bathy,
  depths,
  proj.out = NULL,
  proj.bathy = NULL,
  boundary = NULL,
  warp = FALSE,
  estimate.land = FALSE,
  downsample = NULL,
  verbose = TRUE
)

Arguments

bathy

A stars object or a string giving the path to a bathymetry NetCDF or grd file

depths

Numeric vector giving the cut points for depth contours (see cut). If NULL, no depth aggregation will be made. This option is suitable for raster bathymetries passed directly to basemap.

proj.out

A character string specifying the coordinate reference system (CRS) argument for the output. See st_crs and proj.org. If NULL, the projection is retrieved from bathy and the output will not be reprojected saving processing time (since proj.out and proj.bathy would match.

proj.bathy

A character string specifying the CRS for the input (bathy). Only required if bathy lacks CRS information. If NULL, "EPSG:4326" is assumed.

boundary

A st_polygon object, text string defining the file path to a spatial polygon, bounding box, or a numeric vector of length 4 giving the boundaries for which bathy should be cut to. Should be given as decimal degrees. If unnamed numeric vector, the first element defines the minimum longitude, the second element the maximum longitude, the third element the minimum latitude and the fourth element the maximum latitude of the bounding box. You can also use the sf bounding box format as named vector. Use NULL not to cut bathy.

warp

Logical indicating whether the resulting grid should be resampled to a new CRS if proj.out != proj.bathy using the st_warp function. A time-consuming operation, but necessary when CRS changes in raster bathymetries. Not required if the next step is to vectorise the bathymetry.

estimate.land

Logical indicating whether to include land to the output. Can be used in the following vector_bathymetry step to estimate land polygons.

downsample

An integer defining how many rows in bathy should be skipped to reduce the size (and resolution). 1 skips every second row, 2 every second and third. See st_downsample. Set to NULL (default) to skip downsampling.

verbose

Logical indicating whether information about progress and guessed projection should be returned. Set to FALSE to make the function silent.

Details

You can use GEBCO, IBCAO, ETOPO bathymetry grids downloaded from respective sources as the bathy argument. The bathymetry grids read from files must be in any format read by read_stars. Alternatively use the marmap::getNOAA.bathy function to download ETOPO1 bathymetry and convert it to a raster object using the marmap::as.raster function.

Note that the size of the output is heavily influenced by the number of depth contours (depths) as well as the resolution of bathy and choice of downsample. To make the vector_bathymetry function and consequent plotting faster, limiting the details of the bathymetry raster may be desirable.

Value

A list with a stars object the containing projected bathymetry defined by the proj.out argument and a data frame of depth intervals.

Author(s)

Mikko Vihtakari

References

GEBCO Compilation Group (2019) GEBCO 2019 15-arcsecond grid (doi:10.5285/836f016a-33be-6ddc-e053-6c86abc0788e). URL: https://www.gebco.net/data_and_products/gridded_bathymetry_data/gebco_2019/gebco_2019_info.html. NOAA National Centers for Environmental Information. 2022: ETOPO 2022 15 Arc-Second Global Relief Model. NOAA National Centers for Environmental Information. doi:10.25921/fd45-gt74.

See Also

Other create shapefiles: clip_shapefile(), geonorge_bathymetry(), vector_bathymetry()


Move basemap land, glacier and grid layers on top of other ggplot layers

Description

Moves existing land, glacier and grid layers on top of other layers. Useful for hiding region polygons under land.

Usage

reorder_layers(p)

Arguments

p

ggplot object from the basemap function.

Details

This function has not been tested properly yet and is likely to contain bugs.

Value

Returns a ggplot object with land, glacier and grid layers on top.

Author(s)

Mikko Vihtakari

See Also

Other customize shapefiles: auto_limits(), theme_map()

Examples

if(requireNamespace("ggspatial", quietly = TRUE)) {

 data("ices_areas")
 p <- basemap(c(-20, 15, 50, 70)) + 
   ggspatial::annotation_spatial(ices_areas, aes(fill = Area_Full), show.legend = FALSE)
 
 # Polygons on top of land
 p
 
 # Move land on top
 reorder_layers(p)
 
 }

Rotate CRS

Description

Rotates a CRS such that North is in the middle of two meridians

Usage

rotate_crs(crs, meridians)

Arguments

crs

The CRS to be rotated in st_crs format

meridians

A numeric vector giving the two meridians which should be used in the rotation

Value

Rotated CRS in st_crs format

Author(s)

Mikko Vihtakari


Round to multiple of any number

Description

Round to multiple of any number

Usage

round_any(x, accuracy, f = round)

Arguments

x

numeric vector to round

accuracy

number to round to; for POSIXct objects, a number of seconds

f

rounding function: floor, ceiling or round

Value

Rounded numeric vector

Author(s)

Hadley Wickham


Select an element of each vector from a list

Description

Selects y'th element of each vector from a list

Usage

select_element(x, y)

Arguments

x

list

y

number of element. Must be integer

Value

The selected element from the list


A list of pre-made shapefiles for basemap

Description

Lists available pre-made shapefiles for plotting in the basemap function. Gives also instructions how to make custom ones.

Usage

shapefile_list(name, get.data = FALSE)

Arguments

name

A character argument giving the name of a pre-made shapefile. Will be partially matched. Use "all" to list all available ones.

get.data

Logical indicating whether spatial data should be returned instead of names of spatial data objects.

Details

Custom shapefiles for basemap should be defined as lists with (at least) following names (everything should be provided as characters):

All linked spatial data objects must be in same projection. High-resolution pre-made data are still under development and may not be available. Pre-made shapefiles contain additional elements that are used in the basemap function, but not required for custom shapefile datasets.

Value

Returns a data frame of provided pre-made shapefiles, if name = "all". Returns a shapefile list containing the information for a particular map otherwise.

Author(s)

Mikko Vihtakari

See Also

Other basemap functions: basemap(), qmap(), transform_coord()

Examples

shapefile_list("all")
shapefile_list("Arctic") # partial matching

A ggplot2 theme for maps

Description

A ggplot2 theme for maps.

Usage

theme_map(..., grid.col, grid.size)

Arguments

...

additional arguments passed to ggtheme.

grid.col

Character code specifying the color of grid lines. Use NA to remove the grid lines.

grid.size

Numeric value specifying the width of grid lines.

Value

A ggplot2 theme layer.

See Also

Other customize shapefiles: auto_limits(), reorder_layers()


Transform spatial coordinates to another projection

Description

Transforms spatial coordinates from original projection (decimal degrees assumed) to another projection.

Usage

transform_coord(
  x = NULL,
  lon = NULL,
  lat = NULL,
  new.names = "auto",
  rotate = FALSE,
  proj.in = 4326,
  proj.out = NULL,
  verbose = FALSE,
  bind = FALSE,
  na = "ignore"
)

Arguments

x

Data frame to be transformed. Can be omitted if numeric vectors are assigned to lon and lat.

lon, lat

Either a name of the longitude and latitude columns in x or a numeric vector containing longitude and latitude coordinates. Use NULL to guess the longitude and/or latitude columns in x.

new.names

Character vector of length 2 specifying the names of transformed longitude and latitude columns, respectively. Alternatively NULL, which returns column names from x or "auto", which uses NULL if bind = FALSE and c("lon.proj", "lat.proj") if bind = TRUE.

rotate

Logical indicating whether the projected maps should be rotated to point towards the pole relative to the mid-longitude limit.

proj.in

The original CRS. If NULL, the projection is taken from x. x must be a spatial object in that case.

proj.out

Character. Either NULL, CRS the coordinates should be transformed to or a name of shapefiles in shapefile_list. If NULL, the output projection will be automatically determined from data. This option requires decimal degrees as input option.

verbose

Logical indicating whether information about the projection should be returned as message. Set to FALSE to make the function silent.

bind

logical. Should only transformed coordinates be returned (FALSE, default) or should x be returned with transformed coordinates (TRUE)?

na

character specifying the NA action for missing coordinates. The "ignore" option ignores the coordinates and returns NAs to transformed coordinates. The "remove" option removes missing values from x returning a message while doing it. Any other character argument will trigger na.fail stopping the function in case of missing coordinates.

Details

If x is specified, the function guesses longitude and latitude columns from x by default.

Value

Returns a data frame with transformed spatial coordinates.

Author(s)

Mikko Vihtakari

See Also

Other basemap functions: basemap(), qmap(), shapefile_list()

Examples

# Coordinates are automatically transformed to the pre-made shapefile
# projections:
x <- data.frame(lon = c(-150, 150), lat = c(60, 90))
transform_coord(x)
transform_coord(x, bind = TRUE)

x <- data.frame(lon = c(-150, 150), lat = c(20, 50))
transform_coord(x, bind = TRUE) # no transformation required.

Create a polygon bathymetry from a raster bathymetry file

Description

Vectorizes bathymetry rasters. Designed to be used for the output of raster_bathymetry function. Warning: processing may take a long time if the bathymetry raster is large.

Usage

vector_bathymetry(
  bathy,
  drop.crumbs = NULL,
  remove.holes = NULL,
  smooth = FALSE
)

Arguments

bathy

bathyRaster object from the raster_bathymetry function.

drop.crumbs

Single numeric value specifying a threshold (area in km2) for disconnected polygons which should be removed. Set to NULL to bypass the removal. Uses the drop_crumbs function.

remove.holes

Single numeric value specifying a threshold (area in km2) for holes which should be removed. Set to NULL to bypass the removal. Uses the fill_holes function. Currently VERY slow.

smooth

Logical indicating whether the pixelated contours should be smoothed. Uses the smooth_ksmooth function.

Details

The drop.crumbs and remove.holes arguments can be used to make the resulting object smaller in file size. The smooth argument can be used to remove the pixelated contours, but often increases file size. Note also that using this option will bias the contours with respect to real world.

Value

An sf object containing the depth polygons. Uses same projection than bathy (see CRS).

Author(s)

Mikko Vihtakari

See Also

Other create shapefiles: clip_shapefile(), geonorge_bathymetry(), raster_bathymetry()