我想在使用 ggplot2 繪制的熱圖或柵格中指出一個感興趣的區域。我的用例不是空間資料,而是具有三個變數的連續資料。我想出了一個使用 terra 包的解決方案,但我認為那里必須有一個更優雅或更簡單的解決方案。在下面的示例中,我使用多邊形來指示具有我選擇的某個閾值的區域。
library(ggplot2)
library(dplyr)
library(terra)
data("faithfuld")
# rasterize the data with terra
ncol <- faithfuld |> distinct(waiting) |> nrow()
nrow <- faithfuld |> distinct(eruptions) |> nrow()
xmin <- faithfuld$waiting |> min()
xmax <- faithfuld$waiting |> max()
ymin <- faithfuld$eruptions |> min()
ymax <- faithfuld$eruptions |> max()
faithful_vec <- vect(faithfuld, geom = c("waiting", "eruptions"))
r1 <- rast(ncol=ncol, nrow=nrow, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)
r1 <- rasterize(faithful_vec, r1, "density", mean)
# filter values to highlight
r1[r1 < 0.025] <- NA
# convert to polygon and grab geometry
r2 <- as.polygons(r1) |>
geom() |>
as_tibble()
ggplot()
geom_raster(data = faithfuld, aes(waiting, eruptions, fill = density), interpolate = TRUE)
## highlighted area ##
geom_polygon(data = r2, aes(x, y, group = part), color = "white", fill = "transparent")
scale_fill_viridis_c()

理想情況下,我想要一個不依賴 terra 生成多邊形的解決方案。
uj5u.com熱心網友回復:
您可以geom_contour直接用于此目的,將單個中斷設定為 0.025。它還具有通過插值平滑結果的好處。
library(ggplot2)
library(dplyr)
data("faithfuld")
faithfuld %>%
ggplot(aes(eruptions, waiting, fill = density))
geom_raster(interpolate = TRUE)
scale_fill_viridis_c()
geom_contour(aes(z = density), color = "white", breaks = 0.025)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526995.html
標籤:rggplot2
