I have problems plotting a raster with factor values using ggplot2.
library(ggplot2)
library(raster)
first, load raster data
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)
plot the grid using geom_raster(). Everything works fine.
ggplot(xy, aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal()
I don not have a continuous raster, but a classified. Reclass 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)
plot the classified raster. Also OK, but legend is continuous
ggplot(na.omit(xy), aes(x=x, y=y, fill=val)) + geom_raster() + coord_equal()
if I plot the values as factor, the map becomes wrong
ggplot(na.omit(xy), aes(x=x, y=y, fill=factor(val))) + geom_raster() + coord_equal()
Plotting the 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. Proceeding from a slightly modified version of your code:
I get:
Note that
classify()
has been depreciated andreclassify()
is its substitute.