不幸的是,包作者不再推荐来自 {ggplot2} 的fortify()。 那些包作者也不再推荐来自 {broom} 包的建议替换 tidy()!
幸运的是,我们可以使用 {sf} 包重新创建 Josh O'Brien 的答案。我们仍然依赖 {raster} 包中的一些功能,但一旦修复了假定的错误,这些功能可能可以用 {stars} 包替换(请参阅https://github.com/r-spatial/sf/issues/1389)。如果您的栅格非常大,使用 {stars} 可能会有优势,因为将栅格(或数据框)转换为连续的多边形可能非常慢(请参阅https://gis.stackexchange.com/a/313550/114075)。
这是代码(借用 Josh O'Brien 的设置):
library(raster)
library(rgeos)
library(ggplot2)
library(sf)
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))
## Convert your data.frame to a raster object
r <- raster::rasterFromXYZ(df)
## Extract polygons
pp <- raster::rasterToPolygons(r, dissolve = TRUE)
## Convert SpatialPolygons to a format usable by ggplot2
outline <- sf::st_as_sf(pp)
## Put it all together:
## The polygon "outline" is filled by default so will cover up the
## raster values. Use fill = NA for the geom_sf() to just use the
## gold border color.
ggplot(df) +
geom_raster(aes(x = x, y = y, fill = d)) +
geom_sf(data = outline, size = 1.5, col = "gold", fill = NA)
或者,将sf 对象转换为LINESTRING,则无需在对geom_sf() 的调用中使用fill = NA 参数:
library(raster)
library(rgeos)
library(ggplot2)
library(sf)
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))
## Convert your data.frame to a raster object
r <- raster::rasterFromXYZ(df)
## Extract polygons
pp <- raster::rasterToPolygons(r, dissolve = TRUE)
## Or you can cast to a linestring instead of using a polygon
## and then having to use the fill = NA argument in the
## geom_sf() call
outline <- sf::st_as_sf(pp) %>% st_cast("LINESTRING")
ggplot(df) +
geom_raster(aes(x = x, y = y, fill = d)) +
geom_sf(data = outline, size = 1.5, col = "gold")