【发布时间】:2020-01-14 20:04:21
【问题描述】:
我想绘制一个使用 fastshp 包中的 read.shp 加载的形状文件。但是,read.shp 函数返回列表列表而不是 data.frame。我不确定我需要提取列表的哪一部分才能获得格式正确的 data.frame 对象。已经在stack overflow 上提出了这个确切的问题,但是,该解决方案似乎不再有效(解决方案来自> 7 年前)。非常感谢任何帮助。
remotes::install_github("s-u/fastshp") #fastshp not on CRAN
library(ggplot2);library(fastshp)
temp <- tempfile()
temp2 <- tempfile()
download.file("https://www2.census.gov/geo/tiger/TIGER2017/COUNTY/tl_2017_us_county.zip",temp)
unzip(zipfile = temp, exdir = temp2)
shp <- list.files(temp2, pattern = ".shp$",full.names=TRUE) %>% read.shp(.)
shp 是一个包含大量信息的列表列表。我尝试了之前发布的 SO 中的以下解决方案,但无济于事:
shp.list <- sapply(shp, FUN = function(x) Polygon(cbind(lon = x$x, lat = x$y))) #throws an error here cbind(lon = x$x, lat = x$y) returns NULL
shp.poly <- Polygons(shp.list, "area")
shp.df <- fortify(shp.poly, region = "area")
我还尝试了以下方法:
shp.list <- sapply(shp, FUN = function(x) do.call(cbind, x[c("id","x","y")])) #returns NULL value here...
shp.df <- as.data.frame(do.call(rbind, shp.list))
更新:仍然没有运气,但更接近:
file_shp<-list.files(temp2, pattern = ".shp$",full.names=TRUE) %>%
read.shp(., format = c("table"))
ggplot() +
geom_polygon(data = file_shp, aes(x = x, y = y, group = part),
colour = "black", fill = NA)
看来投影已关闭。我不确定如何订购数据以正确映射,也不确定如何读取 CRS 数据。尝试以下方法无济于事:
file_prj<-list.files(temp2, pattern = ".prj$",full.names=TRUE) %>%
proj4string(.)
【问题讨论】:
-
有兴趣尝试
sf吗?它可以很好地在格式之间转换,并且有一个geom_sf用于绘制sf对象 -
哦,真可惜。你能以某种方式添加一个人们可以复制的例子吗?也许使用随您可以使用的软件包之一附带的 shapefile?
-
@CyrusMohammadian 我刚刚发布了我调查的内容。看一看。我希望这可以指导您。
-
@jazzurro 这太棒了。你真的深入研究了这一点,非常感谢。
-
@CyrusMohammadian 很高兴为您提供帮助。我有机会学习如何以另一种方式绘制地图。 :) 我希望你可以继续使用这个想法。