plot raster factor values with ggplot

2020-06-27 09:31发布

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

标签: r ggplot2 raster
1条回答
时光不老,我们不散
2楼-- · 2020-06-27 09:54

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.

查看更多
登录 后发表回答