问题描述
我偶然发现了库,并根据描述(以及我的快速粗略测试)与相比,它确实可以提高阅读大型shape文件的时间。
我使用
由于中绘制所需的单个数据框。
$ 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:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!