r - 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()
解决方案
如果您将数据作为空间对象获取,这将更容易。然后你可以操纵它们使河流与美国边界相交。
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 日创建
推荐阅读
- javascript - 如何分离图标和输入类型文本框并将div移动到右上角?
- python - Python:PermissionError:[Errno 13] 权限被拒绝:'D:/Documents/1'
- xml - 包含 & 符号的 XML 文件
- python - 几何必须是使用 Cartopy 的点或线串错误
- postgresql - 窗口函数
- node.js - 如何断言应用程序使用 POST 请求向 API 服务器发送正确的数据
- r - 删除特定行之前的观察
- hadoop - 具有许多并行存储桶的 Flink Hadoop Bucketing Sink 性能
- scripting - 如何在网页测试脚本中保存变量
- javascript - 在 React 中通过 map 方法传递 prop