【问题标题】:plot multiple shp file on a graph using spplot in R在 R 中使用 spplot 在图形上绘制多个 shp 文件
【发布时间】:2012-04-04 03:42:32
【问题描述】:

我有 3 个 shp 文件分别代表房子的房子、房间和床。我需要使用 R 将它们绘制在图表上,以便它们相互重叠。我知道在plot 函数中,我可以使用line 在现有绘图的顶部绘制新行,spplot 中是否有任何等价物?谢谢。

【问题讨论】:

  • spplot 的哪些方面是您无法使用基本图完成的?使用 sp 对象,您只需绘制第一个对象,然后使用 add=TRUE 绘制以覆盖其他对象。为什么要将 spplot 加入其中?

标签: r plot ggplot2 gis


【解决方案1】:

这是一种方法,使用 latticeExtra 包中漂亮的 layer() 函数:

# (1) Load required libraries
library(sp)
library(rgeos)        # For its readWKT() function
library(latticeExtra) # For layer()

# (2) Prepare some example data
sp1 = readWKT("POLYGON((0 0,1 0,1 1,0 1,0 0))")
sp2 = readWKT("POLYGON((0 1,0.5 1.5,1 1,0 1))")
sp3 = readWKT("POLYGON((0.5 0,0.5 0.5,0.75 0.5,0.75 0, 0.5 0))")

# spplot provides "Plot methods for spatial data with attributes",
# so at least the first object plotted needs a (dummy) data.frame attached to it.
spdf1 <- SpatialPolygonsDataFrame(sp1, data=data.frame(1), match.ID=1)

# (3) Plot several layers in a single panel
spplot(spdf1, xlim=c(-0.5, 2), ylim=c(-0.5, 2), 
       col.regions="grey90", colorkey=FALSE) +
layer(sp.polygons(sp2, fill="saddlebrown")) +
layer(sp.polygons(sp3, fill="yellow"))

或者,您可以通过spplot()sp.layout= 参数获得相同的结果。 (指定first=FALSE 确保“屋顶”和“门”将绘制在spplot() 的第一个参数给出的灰色正方形之后/上方。)

spplot(spdf1, xlim=c(-0.5, 2), ylim=c(-0.5, 2), 
       col.regions="grey90", colorkey=FALSE,
       sp.layout = list(list(sp2, fill="saddlebrown", first=FALSE),
                        list(sp3, fill="yellow", first=FALSE)))

【讨论】:

    【解决方案2】:

    您可以在spplot 中使用sp.layout 参数。或者,您可以使用 ggplot2。一些示例代码(未经测试):

    library(ggplot2)
    shp1_data.frame = fortify(shp1)
    shp1_data.frame$id = "shp1"
    shp2_data.frame = fortify(shp2)
    shp2_data.frame$id = "shp2"
    shp = rbind(shp1_data.frame, shp2_data.frame)
    
    ggplot(aes(x = x, y = y, group = group, col = id), data = shp) + geom_path()
    

    ggplot2 中,数据中的列与图中的图形比例相关联。在这种情况下,x 是 x 坐标,y 是 y 坐标,group 是 data.frame shp 中的一列,它指定一个点属于哪个多边形,col 是颜色多边形。我使用的几何图形是geom_path,它根据多边形输入data.frame绘制了一系列线条。另一种方法是使用geom_poly,它也支持填充多边形。

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2017-07-20
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多