首页 > 解决方案 > R 空间 - 边界图

问题描述

如何定义一个国家的边界​​,使该国以外的河流不会出现在地图上?下面的图片链接将阐明我的意思:

美国河流

在此处输入图像描述

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()

标签: rggplot2geospatialsf

解决方案


如果您将数据作为空间对象获取,这将更容易。然后你可以操纵它们使河流与美国边界相交。

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()

reprex 包(v0.3.0)于 2019 年 12 月 26 日创建


推荐阅读