Raster coefficient values ​​for the graph using ggplot

I'm having problems building a raster with coefficients using ggplot2.

library(ggplot2) library(raster) 

load raster data first

 f <- system.file("external/test.grd", package="raster") r <- raster(f) 

extract coordinates and values

 val <- getValues(r) xy <- as.data.frame(xyFromCell(r,1:ncell(r))) xy <- cbind(xy,val) 

build the grid using geom_raster (). Everything is working fine.

 ggplot(xy, aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal() 

I do not have a continuous raster, but classified. Expand the raster:

 r <- reclass(r, c(0,500,1, 500,2000,2)) val <- getValues(r) xy <- as.data.frame(xyFromCell(r,1:ncell(r))) xy <- cbind(xy,val) 

draw a classified raster. Also OK, but the legend is continuous

 ggplot(na.omit(xy), aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal() 

If I plot the values ​​as a factor, the map will become wrong

 ggplot(na.omit(xy), aes(x=x, y=y, fill=factor(val))) + geom_raster() + coord_equal() 
+2
source share
1 answer

Building a reclassified plot works for me using R version 2.15.1, ggplot2_0.9.2.1 and raster_2.0-12. If applicable, try updating R, packages, and dependencies. Based on a slightly modified version of your code:

 f <- system.file("external/test.grd", package="raster") r <- raster(f) r <- reclassify(r, c(0,500,1, 500,2000,2)) val <- getValues(r) xy <- as.data.frame(xyFromCell(r,1:ncell(r))) xy <- cbind(xy,val) ggplot(na.omit(xy), aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal() p <- ggplot(na.omit(xy), aes(x=x, y=y, fill=factor(val))) + geom_raster() + coord_equal() try(ggsave(plot=p,<some file>,height=8,width=8)) 

I get: graham jeffries - reclassified raster

Note that classify() depreciating, and reclassify() is its replacement.

+2
source

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


All Articles