'How to draw rectangle around map area in R?
I have a map of the Northern Hemisphere centered around North America. I would like to draw a red rectangle around the USA (this is part of an inset map) however, I can not seem to get geom_rect
to draw the rectangle. Any ideas?
Code to make map:
library(ggplot2)
library(ggspatial)
library(sf)
library(rnaturalearth)
world <- rnaturalearth::ne_countries(scale = "medium",
returnclass = "sf")
ggplot(data = world) +
geom_sf() +
coord_sf(crs = "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs")
This is the code I'm trying to use to get the red rectangle around the USA which is not working:
ggplot(data = world) +
geom_sf() +
coord_sf(crs = "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs") +
geom_rect(aes(xmin = -132, xmax = -69, ymin = 23, ymax = 49), color = "red", inherit.aes = FALSE)
Solution 1:[1]
You can add one more layer of geom_sf and mention its own co-ordinates like this:
a <- st_as_sf(data.frame(plot_id = 1, lat = -100, long = 36),
coords = c("lat", "long"), crs = 4326)
ggplot(data = world) +
geom_sf() +
geom_sf(data = a, shape = 0, size = 35, color = "red", stroke = 2) +
coord_sf(crs = "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs")
You can change the shape as required
Solution 2:[2]
Your problem is that your box is defined in terms of longitude and latitude, but the projection you use is LAEA 1. You can solve the problem by changing your projection to lon/lat:
ggplot() +
geom_sf(data = world) +
geom_rect(aes(xmin = -132, xmax = -69, ymin = 23, ymax = 49), color = "red", fill = NA) +
coord_sf(crs = "+proj=lonlat +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs")
If you need your map to be in LAEA, you need to describe your box in thse terms:
ggplot() +
geom_sf(data = world) +
geom_rect(aes(xmin = -2464417, xmax = 2574417, ymin = -3064417, ymax = 1264417), color = "red", fill = NA) +
coord_sf(crs = "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs")
1 https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Saijr |