Search code examples
rggplot2rasterpercentile

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


I have a raster data and wants to make contour graph similar to the this question enter link description here. I got the code from here. But I want to highlight (colour) the regions which is above 75 percentile and remaining by the simple lines that are shown in picture below. I copied the code from the the above link

enter image description here

Code is folowing

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

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

Let's mock with 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))

Use sf!!

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

#Now work with geom_sf() on your pg object:

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()

I just want to make the picture which is highlighted only the region which is above 75 percentile by this code.


Solution

  • You can set the breaks of geom_contour_filled to start at your 75th centile, and make the NA value of scale_fill_manual transparent. You also need to draw in the default contour lines:

    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()
    

    enter image description here