plot raster factor values with ggplot

可紊 提交于 2019-12-09 13:48:16

问题


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:


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:

Note that classify() has been depreciated and reclassify() is its substitute.



来源:https://stackoverflow.com/questions/9940495/plot-raster-factor-values-with-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!