围绕栅格单元绘制轮廓

Ale*_*man 4 r ggplot2

使用 ggplot2 我想绘制一个多边形(凸包?),它尊重栅格图的单元格边界(使用geom_raster)。我可以使用凸包方法,但它们会通过 xy 坐标而不是围绕光栅图的单元格(对不起,我的术语受到了我的无知的影响)。例如,给定以下具有分类属性的 xy 坐标数据d

df <- data.frame(x = c(295, 300, 305, 310, 295, 300, 305, 310),
                 y = c(310, 310, 310, 310, 315, 315, 315, 315),
                 d = c(2, 2, 2, 1, 2, 1, 1, 1))
Run Code Online (Sandbox Code Playgroud)

我可以使用 ggplot2geom_raster将属性绘制为填充:

ggplot(df, aes(x, y)) +
  geom_raster(aes(fill = d)) +
  coord_fixed()
Run Code Online (Sandbox Code Playgroud)

给予:

在此处输入图片说明

但我想要的是由d. 像这样的东西:

在此处输入图片说明

我可以使用基本 R 和 ggplot2 来做到这一点,还是有办法使用该raster包或其他一些网格/栅格/GIS 包?我更喜欢保持它尽可能简单。

Jos*_*ien 5

您当然可以使用 R 的空间设施来获得这些多边形。这是一种方法:

library(raster)

## Convert your data.frame to a raster object
r <- rasterFromXYZ(df)

## Extract polygons
pp <- rasterToPolygons(r, dissolve=TRUE)

## Convert SpatialPolygons to a format usable by ggplot2
outline <- fortify(pp)

## Put it all together:
ggplot(df, aes(x, y)) +
    geom_raster(aes(fill = d)) +
    coord_fixed() +
    geom_path(aes(x = long, y = lat, group = group), data = outline, 
              size=1.5, col="gold")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明