【问题标题】:How can I plot shapefile loaded through fastshp in ggplot2?如何在 ggplot2 中绘制通过 fastshp 加载的 shapefile?
【发布时间】:2012-04-24 22:17:03
【问题描述】:

我偶然发现了 fastshp 库,根据描述(以及我的快速粗略测试),与 three other methods 相比,它确实提供了读取大型 shapefile 的时间。

我正在使用read.shp 函数从 maptools 包中加载示例数据集:

library("maptools")

setwd(system.file("shapes", package="maptools"))

shp <- read.shp("columbus.shp", format="polygon")

根据docs,我选择了“多边形”格式:

这通常是首选的绘图格式。

我的问题是如何使用 ggplot2 包绘制这些多边形?

【问题讨论】:

    标签: r ggplot2 shapefile


    【解决方案1】:

    由于fastshp 包中的read.shp 以列表列表的形式返回多边形数据,因此只需将其缩减为在ggplot2 中绘图所需的单个数据帧。

    library(fastshp)
    library(ggplot2)
    
    setwd(system.file("shapes", package="maptools"))
    
    shp <- read.shp("columbus.shp", format="polygon")
    shp.list <- sapply(shp, FUN = function(x) do.call(cbind, x[c("id","x","y")]))
    shp.df <- as.data.frame(do.call(rbind, shp.list))
    shp.gg <- ggplot(shp.df, aes(x = x, y=y, group = id))+geom_polygon()
    

    编辑:根据@otsaw 关于多边形孔的评论,以下解决方案需要更多步骤,但确保最后绘制孔。它利用 shp.df$hole 是合乎逻辑的,并且带有 hole==TRUE 的多边形将最后绘制。

    shp.list <- sapply(shp, FUN = function(x) Polygon(cbind(lon = x$x, lat = x$y)))
    shp.poly <- Polygons(shp.list, "area")
    shp.df <- fortify(shp.poly, region = "area")
    shp.gg <- ggplot(shp.df, aes(x = long, y=lat, group = piece, order = hole))+geom_polygon()
    

    【讨论】:

    • @otsaw:我添加了一种可以正确渲染孔的替代方法
    • @JimM。完美运行。非常感谢您的帮助!
    • @JimM。这是一个很好的解决方案,但不幸的是不再有效。是否有替代工作流程来获取格式正确的 data.frame?刚刚发布:stackoverflow.com/questions/59741003/…
    • @CyrusMohammadian:现在,我可能会使用 sf 包(即通过 st_read 读取 shapefile),可以使用 ggplot 和 geom_sf 进行绘制:cran.r-project.org/web/packages/sf/vignettes/sf5.html#ggplot2
    • @JimM。是的,我多年来一直使用rgdal 和最近的sf,正如您在ggplot2 中提到的geom_sf,但我目前无法安装非R 依赖项,需要一个不依赖于的解决方案sf 使用的 gdal 或 C 库
    猜你喜欢
    • 2022-08-14
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多