将数据连接到.kmz或.kml并绘图

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

我对R来说有点新,并且对地理空间来说是全新的。我正在尝试阅读可下载的.kml,将我自己的数据加入其中,并绘制数据。

.kml来自这个主页:https://www.cnrfc.noaa.gov/ - 地图下方“下载叠加文件”下拉菜单中的“Drainage Basins”图层(文件大小很小)。

library(rgdal)
library(tidyverse)

# read in the downloaded file
# downloads as "basins.kml", "layer name ID'd from viewing .kml as text
spatialpolydf <- readOGR("basins.kml", "cnrfc_09122018_basins_thin")

#view the polygons (california river basins)
ggplot() + geom_path(data = spatialpolydf, aes(x=long, y=lat, group = group))  +
           coord_quickmap()

#create example observations for the 339 river basins
observation_value2 <- sample(1:1000, 339)

#get the basin names #not sure this is reliable
observation_place <- spatialpolydf@data 

#create data.frame for joining to the spatial data frame
#but, I'm not sure I quite need a data.frame, maybe just a tibble or data.table?

obs_place_value <- data.frame(observation_place, observation_value2)

所以从这里开始,我希望能够使用上面的库或任何其他库来加入和可视化观察,例如:

spatialpolydf_withjoineddata <- some_join_function(obs_place_value,
                                                   spatialpolydf)
ggplot() + geom_path(data = spatialpolydf_withjoineddata, aes(x=long, y=lat,
           group = group, fill = observation_value2))  + coord_quickmap()

有一个339行数据的对象/ data.frame似乎很不错,其中每行可以表示像ESRI属性表那样的多个多边形,隐藏了通常不需要的几何数据。我对所有建议持开放态度,但理想情况下,我将学习将数据保留为可用/灵活格式以便以后处理/可视化的方法,而不是仅仅为了查看这些数据而快速修复。

enter image description here

r rgdal sf
1个回答
1
投票

你用sf标签标记了你的问题,所以我想你可能想了解更多关于sf的信息。下面是一个脚本,用于将sp对象转换为sf对象,连接数据框obs_place_value,然后使用observation_value2将数据可视化为填充值。 sf对象是一种特殊的数据框架,因此像left_join这样的数据框架上的函数也可以在sf对象上工作。 geom_sf是绘制sf对象的函数。

library(rgdal)
library(tidyverse)
library(sp)
library(sf)

# read in the downloaded file
# downloads as "basins.kml", "layer name ID'd from viewing .kml as text
spatialpolydf <- readOGR("Data/basins.kml", "cnrfc_09122018_basins_thin")

# set.seed for reproducibility
set.seed(123)

#create example observations for the 339 river basins
observation_value2 <- sample(1:1000, 339)

#create data.frame for joining to the spatial data frame
obs_place_value <- data.frame(observation_place, observation_value2)

# Convert spatialpolydf to an sf object
spatialpolysf <- spatialpolydf %>% st_as_sf()

# Join the data
spatialpolysf2 <- spatialpolysf %>%
  left_join(obs_place_value, by = c("Name", "Description"))

# Use ggplot2 to plot the data
ggplot(spatialpolysf2) +
  geom_sf(aes(fill = observation_value2))

enter image description here

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