如何制作仅对特定区域着色的等高线图?

How to make contour lines graph which colored only certain region?

我有一个栅格数据,想制作类似于这个问题的等高线图。我从这里得到了代码。但我想突出显示(颜色) 高于 75 个百分点并由下图所示的简单线条保留的区域。 我复制了上面的代码link

enter image description here

代码如下

library(raster)
library(sf)
library(sp)

r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))

让我们用 shapefile 模拟一下

poly <- st_as_sfc(st_bbox(st_as_sf(rasterToPolygons(r))))

set.seed(3456)

sample <- st_sample(poly, 4)
sample <- st_buffer(sample, c(0.01, 0.02, 0.03))
sample <- st_sf(x=1:4, sample)
st_write(sample, "1aa.shp", append = FALSE)

 library(raster)
 library(sf)

 r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))

使用 sf!!

 pg <- st_read("1aa.shp") # loadshapfile 
 plot(r)
 plot(st_geometry(pg), add= TRUE,) 

#现在在你的 pg 对象上使用 geom_sf():

centile90 <- quantile(r, 0.90)
df <- as.data.frame(as(r, "SpatialPixelsDataFrame"))
colnames(df) <- c("value", "x", "y")

library(ggplot2)

mybreaks <- seq(0, 500, 50)

ggplot(df, aes(x, y, z = value)) +
 geom_contour_filled(breaks = mybreaks) +
 geom_contour(breaks = centile90, colour = "pink",
           size = 0.5) +

 geom_sf(data=pg, fill="black", inherit.aes = FALSE) +
 scale_fill_manual(values = hcl.colors(length(mybreaks)-1, "Zissou1", rev = FALSE)) +
 scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
 theme_classic() +
 theme()

我只是想通过这段代码使图片只突出显示 75% 以上的区域。

您可以将 geom_contour_filled 的中断设置为从第 75 个百分位数开始,并使 scale_fill_manualNA 值透明。您还需要绘制默认轮廓线:

centile75 <- quantile(r, 0.75)

ggplot(df, aes(x, y, z = value)) +
 geom_contour(color = 'gray') +
 geom_contour_filled(breaks = seq(centile70, max(df$value), length = 5)) +
 geom_sf(data=pg, fill="black", inherit.aes = FALSE) +
 scale_fill_manual(
   values = hcl.colors(4, "Zissou1"),
   na.value = "#00000000") +
 scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
 theme_classic() +
 theme()