Maps in R

rstudio rmarkdown
mapping

Making maps in RStudio

Author

Siobhon Egan

Published

February 13, 2021

πŸ”— Links to get to started for mapping in RStudio

πŸ”— Useful data sets for mapping


Example workflow 1

Following tutorial at this link

library(sp)
library(dplyr)
library(rgdal)
library(raster)
library(ggplot2)
library(readr)

Import csv file containing lon and lat coords

Sites <- read_csv("sites.csv")

Create buffer around your data points

buffer <- 0.11
geo_bounds <- c(
  left = min(Sites$Lon) - buffer,
  bottom = min(Sites$Lat) - buffer,
  right = max(Sites$Lon) + buffer,
  top = max(Sites$Lat) + buffer
)
Sites.grid <-
  expand.grid(
    lon_bound = c(geo_bounds[1], geo_bounds[3]),
    lat_bound = c(geo_bounds[2], geo_bounds[4])
  )

coordinates(Sites.grid) <- ~ lon_bound + lat_bound

Load mapping files Downloaded from GEODATA COAST 100K 2004 shapefiles available here

Aus <-
  readOGR(dsn = "~/Documents/Programs/R/Maps/Rpackage_Geodata-coast/australia", layer = "cstauscd_r")

Remove coastline clutter from map

Aus_coast <- subset(Aus, FEAT_CODE != "sea")
plot(Aus_coast)

Plot map and points using ggplot2

g1 <- ggplot(data = Aus_coast) +
  geom_polygon(aes(x = long, y = lat, group = group),
               fill = NA,
               color = "black") +
  coord_fixed(1.3) + theme_classic()

g2 <- g1 + geom_point(data = Sites, aes (
  x = Lon,
  y = Lat,
  colour = Locality,
  stroke = 1.5
)) +
  scale_colour_viridis_d(option = "plasma")

Customise colour of points

g3 <-  g1 + geom_point(data = Sites,
                     aes (
                       x = Lon,
                       y = Lat,
                       colour = Locality,
                       stroke = 1.5
                     ),
                     colour = "#CC0000")

Make interactive plot with plotly

library(plotly)
gp <- ggplotly(g3)
gp

To save a html version of the interactive plot execute the following

htmlwidgets::saveWidget(gp, "index.html")
gp

Example workflow 2

Tutorial from Displaying Geo-Spatial Data with R by Martin Schweinberger

Install packages

# clean current workspace
rm(list = ls(all = T))
# set options
options(stringsAsFactors = F)         # no automatic data transformation
options("scipen" = 100, "digits" = 4) # suppress math annotation
op <- options(gvis.plot.tag = 'chart')  # set gViz options
# install libraries
install.packages(
  c(
    "RgoogleMaps",
    "ggmap",
    "mapproj",
    "sf",
    "dplyr",
    "OpenStreetMap",
    "devtools",
    "DT"
  )
)
# install package from github
devtools::install_github("dkahle/ggmap", ref = "tidyup")

Load library and produce simple map of Australia

# load library
library(OpenStreetMap)
# extract map
AustraliaMap <- openmap(c(-8, 110),
                        c(-45, 160),
                        type = "osm",
                        #   type = "esri",
                        #    type = "nps",
                        minNumTiles = 7)
# plot map
plot(AustraliaMap)