Build continuous raster data in binned classes with ggplot2 in R

I really like the look of ggplot2 and often use them to display raster data (for example, time- ggplot2 for time-varying precipitation fields is very useful).

However, I am still wondering if it is easy to output continuous raster values ​​into discrete cells and assign each box one color , which is shown in the legend (as many GIS systems).

I tried with the arguments guide = "legend" and breaks the scale_fill_gradient parameter. However, they only affect the legend on the side of the chart, but the plotted values ​​are still continuous.

 library(ggplot2) data <- data.frame(x=rep(seq(1:10),times = 10), y=rep(seq(1:10),each = 10), value = runif(100,-10,10)) ggplot(data = data, aes(x=x,y=y)) + geom_raster(aes(fill = value)) + coord_equal() + scale_fill_gradient2(low = "darkred", mid = "white", high = "midnightblue", guide = "legend", breaks = c(-8,-4,0,4,8)) 

My question basically is how to discretize data built in ggplot so that the graph reader can draw quantitative conclusions about the values ​​represented by colors.

Secondly, how can I use a diverging color palette (similar to scale_fill_gradient2 ) that is centered around zero or another specific value?

+5
source share
1 answer

You must use the raster package to work with raster data. This package provides several functions for working with categorical rasters. For example, with reclassify you can convert a continuous file to a discrete raster. The following example is adapted from this question :

 library(raster) f <- system.file("external/test.grd", package="raster") r <- raster(f) r <- reclassify(r, c(0, 500, 1, 500, 2000, 2)) 

On the other hand, if you want to use the ggplot2 functions, the rasterVis package provides a simple wrapper around ggplot that works with RasterLayer objects:

 library(rasterVis) gplot(r) + geom_raster(aes(fill = factor(value))) + coord_equal() 

ggplot with raster

To define your own colors, which you can add then:

 scale_fill_manual(values=c('red','green'))) 
+6
source

Source: https://habr.com/ru/post/1200196/


All Articles