Reputation: 13
How can I define the boundaries of a country, so rivers outside the country won't appear on the map? The image link below will clarify what I mean:
library(tidyverse) # ggplot2, dplyr, tidyr, readr, purrr, tibble
library(magrittr) # pipes
library(rnaturalearth) # Rivers
library(urbnmapr)
states <- urbnmapr::states
states <- fortify(states)
rivers10 <- ne_download(scale = "medium", type = 'rivers_lake_centerlines', category = 'physical') #, returnclass = "sf"
rivers10 <- fortify(rivers10)
rivers10 <- rivers10 %>%
filter(long >= min(states$long)) %>%
filter(long <= max(states$long)) %>%
filter(lat >= min(states$lat)) %>%
filter(lat <= max(states$lat))
ggplot() +
geom_polygon(data = urbnmapr::states, mapping = aes(x = long, y = lat, group = group),
fill = "#CDCDCD", color = "#25221E") +
coord_map(projection = "albers", lat0 = 39, lat1 = 45) +
geom_path(data = rivers10,
aes(long, lat, group = group), size = 1, color = '#000077') +
theme_minimal()
Upvotes: 1
Views: 347
Reputation: 3388
This is easier if you get the data as spatial objects. Then you can manipulate them to intersect the rivers with the US boundary.
library(tidyverse) # ggplot2, dplyr, tidyr, readr, purrr, tibble
library(rnaturalearth) # Rivers
library(sf)
library(urbnmapr)
states = get_urbn_map('states', sf=TRUE)
rivers10 <- ne_download(scale = "medium", type = 'rivers_lake_centerlines',
category = 'physical', returnclass = "sf")
# Outline of the US
us = st_union(states)
# Transform rivers to the same projection as states and clip to US
rivers10 <- rivers10 %>%
st_transform(st_crs(states)) %>%
st_intersection(us)
ggplot() +
geom_sf(data=states, fill = "#CDCDCD", color = "#25221E") +
geom_sf(data=rivers10, color='#000077') +
theme_minimal()
Created on 2019-12-26 by the reprex package (v0.3.0)
Upvotes: 3