我有一些坐标,说:
library(tidyverse)
library(haven)
library(tidycensus)
library(tigris)
coords <- data.frame(lat = c(38.09720, 36.85298, 31.31517, 21.48344), long = c(-121.38785, -75.97742, -85.85522, -158.03648))
然后我得到了一张美国地图:
geo <- get_acs(geography = "state",
variables = c(x = "B04006_036"),
year = 2021,
geometry = TRUE,
keep_geo_vars=TRUE) %>%
filter(STATEFP!="72")
#to get alaska and hawaii in the picture
geo <- shift_geometry(geo)
然后我尝试绘制州地图,并覆盖坐标:
ggplot(data = coords) +
geom_point(aes(x=lat, y=long)) +
geom_sf(fill = "transparent", color = "gray50", size = 1, data = geo %>% group_by(STATEFP) %>% summarise()) +
theme(panel.background = element_rect(fill = 'white')) +
theme(panel.grid = element_blank(),axis.title = element_blank(),
axis.text = element_blank(),axis.ticks = element_blank(),
panel.border = element_blank())
这会产生:
但是,这不起作用,因为它会生成一个所有坐标似乎都在同一位置的地图。如何修改以使地图和坐标处于相同比例?
这根本就是投影错误!您需要告诉 R(更具体地说 sf)您的坐标所在的投影。我假设它们位于典型的 WGS 1984 (EPSG:4326) 中。然后我们可以从您的
coords
df 创建一个 sf 对象并像 geom_sf 一样绘制。
library(tidyverse)
library(haven)
library(tidycensus)
library(tigris)
library(sf)
coords <- data.frame(lat = c(38.09720, 36.85298, 31.31517, 21.48344), long = c(-121.38785, -75.97742, -85.85522, -158.03648)) |>
st_as_sf(coords = c("long", "lat"), crs = 4326)
geo <- get_acs(geography = "state",
variables = c(x = "B04006_036"),
year = 2021,
geometry = TRUE,
keep_geo_vars=TRUE) %>%
filter(STATEFP!="72")
#to get alaska and hawaii in the picture
geo <- shift_geometry(geo)
ggplot(data = coords) +
geom_sf(data = shift_geometry(coords)) +
geom_sf(fill = "transparent", color = "gray50", size = 1, data = geo %>% group_by(STATEFP) %>% summarise()) +
theme(panel.background = element_rect(fill = 'white')) +
theme(panel.grid = element_blank(),axis.title = element_blank(),
axis.text = element_blank(),axis.ticks = element_blank(),
panel.border = element_blank())