gpt4 book ai didi

r - 如何在 ggplot2 中绘制通过 fastshp 加载的 shapefile?

转载 作者:行者123 更新时间:2023-12-02 10:44:10 25 4
gpt4 key购买 nike

我偶然发现fastshp库,根据描述(以及我的快速粗略测试),与 three other methods 相比,它确实在读取大型形状文件方面提供了改进。 .

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

library("maptools")

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

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

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

This is typically the preferred format for plotting.

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

最佳答案

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

关于r - 如何在 ggplot2 中绘制通过 fastshp 加载的 shapefile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10306831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com