我怎样才能通过ggplot2中的fastshp来绘制shapefile? [英] How can I plot shapefile loaded through fastshp in ggplot2?

查看:353
本文介绍了我怎样才能通过ggplot2中的fastshp来绘制shapefile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了 fastshp 库,并根据描述(以及我的快速粗略测试)与其他三种方法相比,它确实可以提高阅读大型shape文件的时间。



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

  library(maptools)

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

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

我选择了多边形格式,因为符合 docs
$ b


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


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

解决方案

由于 read.shp $ c> fastshp package以列表的形式返回多边形数据,然后将它缩小为 ggplot2 中绘制所需的单个数据框。

$ p $ 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< - 多边形(shp.list,area)
shp.df< - 强化(shp.poly,region =area)
shp.gg< - ggplot(shp.df,aes(x = long,y = lat,group = piece,order = hole))+ geom_polygon()


I stumbled upon fastshp library and according to description (and my quick cursory tests) it really does offer improvements in time of reading large shapefiles compared to three other methods.

I'm using read.shp function to load exemplary dataset from maptools package:

library("maptools")

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

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

I chose 'polygon' format since accordng to docs:

This is typically the preferred format for plotting.

My question is how can I plot these polygons using ggplot2 package?

解决方案

Since read.shp in the fastshp package returns the polygon data in the form of a list of lists, it is then a matter of reducing it to a single dataframe required for plotting in 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()

EDIT: Based on @otsaw's comment regarding polygon holes, the following solution requires a couple of more steps but ensures that the holes are plotted last. It takes advantage that shp.df$hole is logical and polygons with hole==TRUE will be plotted last.

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

这篇关于我怎样才能通过ggplot2中的fastshp来绘制shapefile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆