2012-04-24 30 views
3

我偶然發現了fastshp庫,根據描述(以及我的快速粗略測試),與three other methods相比,它確實提供了讀取大型shape文件的時間改進。如何繪製通過ggplot2中的fastshp加載的shapefile?

我使用read.shp函數從maptools包加載的示例性數據集:

library("maptools") 

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

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

我選擇「多邊形」格式自accordng到docs

這通常是用於繪製的優選格式。

我的問題是如何使用ggplot2軟件包繪製這些多邊形?

回答

3

由於read.shpfastshp包中列表的列表的形式返回多邊形數據,它是那麼它減少用於在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() 
+2

這是否能正確渲染孔? – otsaw 2012-04-25 09:17:19

+0

@otsaw:我已經添加了一個替代方法,可以正確渲染空洞 – 2012-04-25 17:38:19

+0

@JimM。完美的作品。非常感謝您的幫助! – radek 2012-04-25 21:16:43