2

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

1 Answer 1

2

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:

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() has been depreciated and reclassify() is its substitute.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.