在R中将几何坐标映射到地图对象

3

我试图将一些几何点或坐标映射到斯里兰卡国家地图上。我能够按预期绘制区域边界和人口,但是我无法将几何点绘制在地图上。

安装包

devtools::install_github("thiyangt/ceylon")

加载软件包

library("ceylon")
library(tidyverse)
library(sp)
library(viridis)

data(sf_sl_0)

仅映射斯里兰卡

ggplot(sf_sl_0) + geom_sf()

在斯里兰卡绘制行政区划地图+人口统计

ggplot(district) + geom_sf(aes(fill = population), show.legend = TRUE) +  scale_fill_viridis()

将特定的地理坐标映射到斯里兰卡区域地图上

我希望将以下这些坐标映射到地图中(是的,它们肯定在斯里兰卡境内)

df_cord <- data.frame (lat  = c("6.2441521", "6.2234515"),
                  lon = c("80.0590804", "80.2126109"))

我尝试过:

ggplot(district) + 
  geom_sf(df_cord) +  scale_fill_viridis() +
  geom_point(
    data = df_cord,
    aes(x = lon, y = lat),
    size = 4,
    shape = 23,
    fill = "darkred"
  )

但是我遇到了一个错误:validate_mapping() 中的错误: !mapping 必须由 aes() 创建

看起来我可能需要找到每个几何点的 x,y 坐标,然后再使用 cord_sf 进行映射?但是我无法弄清楚如何做到这一点。我发现了一个很酷的函数叫做 usmap::usmap_transform,它可以将美国几何点转换为 x,y 坐标... 但我无法弄清楚如何在斯里兰卡地图上实现相同的功能。

我对地图制作非常陌生--请问有人可以给予建议吗?非常感谢!我也会接受其他方法/解决方案的建议!

3个回答

3

一种方法是使用st_as_sf将坐标转换为sf对象,并使用geom_sf进行绘图。不要忘记将数据重新投影到相同的坐标系:

library(ceylon)
library(tidyverse)
library(sp)
library(viridis)
library(sf)

data(district)

df_cord <- data.frame (lat  = c(6.2441521, 6.2234515),
                       lon = c(80.0590804, 80.2126109))

df_cord  <- df_cord %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  st_transform(crs = st_crs(district)) #reproject coords using the coordinate system of the polygons

#plot

ggplot(district) + 
  geom_sf(aes(fill = population),  show.legend = TRUE) +
  geom_sf(data = df_cord ,
          size = 4,
          shape = 23,
          fill = "darkred") +
  scale_fill_viridis() 

enter image description here


0

我认为你不能在ggplot中分配两个数据框。

将纬度和经度值放入geom_point的aes()中。请记住,经度是x轴,纬度是y轴。

试试这个:

ggplot() +  
  geom_sf(district) +
  scale_fill_viridis() +
  geom_point(
    aes(x = c("80.0590804", "80.2126109"), 
        y =c("6.2441521", "6.2234515")),
    size = 4,
    shape = 23,
    fill = "darkred"
  )

感谢您的建议,但是在运行您的代码时出现了错误:check_aesthetics()中的错误: !美学元素必须是长度为1或与数据(26)相同:x和y。 - NewBee
刚刚编辑了答案并提供了其他建议。再试一次吧 :P - Lucca Nielsen
仍然在validate_mapping()中遇到错误: !mapping必须由aes()创建 - NewBee

0

您可以添加注释(annotate),这将显示您的两个坐标。此外,像这样设置正确的坐标系:

ggplot(district) + 
  geom_sf(aes(fill = population), show.legend = TRUE) +  
  annotate("point", x = 80.0590804, y = 6.2441521, colour = "red", size = 2) +
  annotate("point", x = 80.2126109, y = 6.2234515, colour = "red", size = 2) +
  coord_sf(default_crs = sf::st_crs(4326)) +
  scale_fill_viridis()

输出:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接