如何获取与州边界图相同坐标系上的经纬度坐标

问题描述 投票:0回答:1

我有一些坐标,说:

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

这会产生:

enter image description here

但是,这不起作用,因为它会生成一个所有坐标似乎都在同一位置的地图。如何修改以使地图和坐标处于相同比例?

r ggplot2 tidyverse coordinates latitude-longitude
1个回答
0
投票

这根本就是投影错误!您需要告诉 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())

correct map

© www.soinside.com 2019 - 2024. All rights reserved.