Work code - see the slides for the final code.
cf. - https://r-spatial.org/r/2018/10/25/ggplot2-sf.html - https://paleolimbot.github.io/ggspatial/
ggplot does ok.
library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
## v ggplot2 3.3.5 v purrr 0.3.4
## v tibble 3.1.6 v dplyr 1.0.7
## v tidyr 1.1.4 v stringr 1.4.0
## v readr 2.1.0 v forcats 0.5.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
library(sf)
## Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
library(rnaturalearth)
library(rnaturalearthdata)
world <- ne_countries(scale = "medium", returnclass = "sf")
world %>%
ggplot() +
geom_sf() +
coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97))
ggspatial adds ggplot-compatible mapping features.
library(ggspatial)
plot(world$geometry)
# world_points <- cbind(world, st_coordinates(st_centroid(world$geometry)))
world %>%
ggplot() +
geom_sf() +
coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97)) +
annotation_scale(location = "bl", width_hint = 0.5) +
annotation_north_arrow(location = "tr") +
annotate(geom = "text", x = -90, y = 26, label = "Gulf of Mexico",
fontface = "italic", color = "grey22", size = 5)
## Scale on map varies by more than 10%, scale bar may be inaccurate
# geom_text(data = world_points, aes(x=X, y=Y, label=name),
# color = "darkblue", fontface = "bold", check_overlap = FALSE)
cities <- data.frame(
x = c(-63.58595, 116.41214),
y = c(44.64862, 40.19063),
city = c("Halifax", "Beijing")
)
ggplot(cities, aes(x, y)) +
annotation_map_tile(type = "stamenwatercolor") +
geom_spatial_point() +
geom_spatial_label_repel(aes(label = city), box.padding = 1) +
coord_sf(crs = 3995)
## Assuming `crs = 4326` in stat_spatial_identity()
## Assuming `crs = 4326` in stat_spatial_identity()
## Loading required namespace: raster
## Zoom: 1