I have a raster image whose value ranges from 1 to 10. I want to find the 90 percentile of mine raster data. And need to find the contour graph by highlighting the area having the 90 percentile. I want a figure for my raster data is attached below. I am doing my analysis in R.
library(raster)
library(cartography)
library(sf)
library(SpatialPosition)
r <- raster("E:/data.tif", package="raster")
plot(r)
contour(r, add=TRUE)
I got this type of image, but I wants the one with a shaded one (right side). Help on making this picture will be much appreciated.
CodePudding user response:
Obviously, don't have your data, but we can make an example raster like this:
r <- raster(t(volcano[,ncol(volcano):1]))
From now on, the following code should work with your own raster too. We can get the 90th centile of our data like this:
centile90 <- quantile(r[], 0.9)
Now let's convert the raster to an x, y, z data frame:
df <- as.data.frame(as(r, "SpatialPixelsDataFrame"))
colnames(df) <- c("value", "x", "y")
We can use the feature-rich ggplot2
library for drawing the data. We will plot as a filled contour map and add a bright green contour at our 90th centile:
library(ggplot2)
ggplot(df, aes(x, y, z = value))
geom_contour_filled(bins = 10)
geom_contour(breaks = centile90, colour = "green",
size = 2)
scale_fill_manual(values = hcl.colors(10, "YlOrRd", rev = TRUE))
scale_x_continuous(expand = c(0, 0))
scale_y_continuous(expand = c(0, 0))
theme_classic()
theme(legend.position = "none")