好的,我明白了。您想要在 ggplot 上绘制多个栅格图层,或者希望栅格对象位于背景多边形对象上方。问题在于rasterVis::gplot
是它直接绘制栅格并且不允许在下面或上面添加另一个栅格。你提醒我我已经有这个需求并修改了功能gplot
以 tibble 的形式检索数据,以便您可以随心所欲地使用它dplyr
进而ggplot2
。感谢提醒,我将其添加到我当前的github库中以供以后使用!
让我们使用一个可重现的示例来展示此功能:
创建数据集
- 创建世界地图作为
Raster
用作背景光栅图
- 创建数据栅格,这里是距点的距离(限制为最大距离)
代码:
library(raster)
# Get world map
library(maptools)
data(wrld_simpl)
# Transform World as raster
r <- raster(wrld_simpl, res = 1)
wrld_r <- rasterize(wrld_simpl, r)
# Lets create a raster of data
pt1 <- matrix(c(100,0), ncol = 2)
dist1 <- distanceFromPoints(r, pt1)
values(dist1)[values(dist1) > 5e6] <- NA
plot(dist1)
# Plot both
plot(wrld_r, col = "grey")
plot(dist1, add = TRUE)
提取(部分)栅格值并将其转换为 tibble 的函数
#' Transform raster as data.frame to be later used with ggplot
#' Modified from rasterVis::gplot
#'
#' @param x A Raster* object
#' @param maxpixels Maximum number of pixels to use
#'
#' @details rasterVis::gplot is nice to plot a raster in a ggplot but
#' if you want to plot different rasters on the same plot, you are stuck.
#' If you want to add other information or transform your raster as a
#' category raster, you can not do it. With `SDMSelect::gplot_data`, you retrieve your
#' raster as a tibble that can be modified as wanted using `dplyr` and
#' then plot in `ggplot` using `geom_tile`.
#' If Raster has levels, they will be joined to the final tibble.
#'
#' @export
gplot_data <- function(x, maxpixels = 50000) {
x <- raster::sampleRegular(x, maxpixels, asRaster = TRUE)
coords <- raster::xyFromCell(x, seq_len(raster::ncell(x)))
## Extract values
dat <- utils::stack(as.data.frame(raster::getValues(x)))
names(dat) <- c('value', 'variable')
dat <- dplyr::as.tbl(data.frame(coords, dat))
if (!is.null(levels(x))) {
dat <- dplyr::left_join(dat, levels(x)[[1]],
by = c("value" = "ID"))
}
dat
}
在 ggplot 中绘制多个栅格
您可以使用gplot_data
将任何栅格转换为小标题。然后您可以使用添加任何修改dplyr
并绘制在ggplot
with geom_tile
。有趣的是你可以使用geom_tile
使用不同的栅格数据可以多次使用,前提是fill
选项具有可比性。否则,您可以使用以下技巧来删除NA
背景栅格图中的值并使用唯一的fill
colour.
# With gplot_data
library(ggplot2)
# Transform rasters as data frame
gplot_wrld_r <- gplot_data(wrld_r)
gplot_dist1 <- gplot_data(dist1)
# To define a unique fill colour for the world map,
# you need to remove NA values in gplot_wrld_r which
# can be done with dplyr::filter
ggplot() +
geom_tile(data = dplyr::filter(gplot_wrld_r, !is.na(value)),
aes(x = x, y = y), fill = "grey20") +
geom_tile(data = gplot_dist1,
aes(x = x, y = y, fill = value)) +
scale_fill_gradient("Distance",
low = 'yellow', high = 'blue',
na.value = NA) +
coord_quickmap()
在多边形上绘制栅格
当然,当背景地图作为多边形对象时,这个技巧还可以让您在其上添加光栅:
wrld_simpl_sf <- sf::st_as_sf(wrld_simpl)
ggplot() +
geom_sf(data = wrld_simpl_sf, fill = "grey20",
colour = "white", size = 0.2) +
geom_tile(data = gplot_dist1,
aes(x = x, y = y, fill = value)) +
scale_fill_gradient("Distance",
low = 'yellow', high = 'blue',
na.value = NA)
EDIT: gplot_data
现在在这个简单的 R 包中:https://github.com/statnmap/cartomisc