我有以下代码,可用于创建纽约市 061 和 047 县的地图:
library(tidycensus)
library(tidyverse)
library(tigris)
ny_data <- get_acs(
geography = "tract",
variables = "B19013_001",
state = "NY",
county = c("061","047"),
year = 2019,
geometry = TRUE,
cb = FALSE) %>%
st_transform(26918) %>%
erase_water(year = 2019)
ggplot(data=ny_data, aes(fill = estimate)) +
geom_sf(color = NA) +
scale_fill_viridis_c(option = "magma") +
theme_minimal() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
但是,我想稍微放大这张地图。我知道我应该使用 coord_sf 函数。但是,当我将该函数添加到我的 ggplot 中时,我得到了意想不到的结果:
ggplot(data=ny_data, aes(fill = estimate)) +
geom_sf(color = NA) +
coord_sf(xlim = c(-74.05, -73.9), ylim = c(40.55, 40.85)) +
scale_fill_viridis_c(option = "magma") +
theme_minimal() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
我怀疑这可能与坐标系有关,但我对地理空间数据不太了解,也不知道如何解决它。这也可能与用来帮助我擦除水域的“st_transform”函数有关。任何帮助将不胜感激。
总结: 我尝试使用 coord_sf 函数放大地图区域,纬度和经度的 x 和 y 限制无法按预期工作。
我已经解决了我自己的问题,在这里发布给可能有同样问题的其他人。
如上所述,问题出在“st_transform”函数中。我相信(但不确定)该函数本质上是将我的纽约县 061 和 047 的地理数据转换为整个纽约州的投影(26918 是纽约的 EPSG 代码https://epsg.io/26918 )。
此代码有效:
ny_data <- get_acs(
geography = "tract",
variables = "B19013_001",
state = "NY",
county = c("061","047"),
year = 2019,
geometry = TRUE,
cb = FALSE) %>%
#st_transform(26918) %>%
erase_water(year = 2019)
ggplot(data=ny_data, aes(fill = estimate)) +
geom_sf(color = NA) +
coord_sf(xlim = c(-74.05, -73.9), ylim = c(40.6, 40.85)) +
scale_fill_viridis_c(option = "magma") +
theme_minimal() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))