Plot continuous raster data in binned classes with ggplot2 in R

狂风中的少年 提交于 2019-11-30 20:40:31
Oscar Perpiñán

You should use the raster package to work with raster data. This package provides several function to work with categorical rasters. For example, with reclassify you can convert a continuous file into a discrete raster. The next example is adapted from this question:

library(raster)

f <- system.file("external/test.grd", package="raster")
r <- raster(f)
r <- reclassify(r, c(0, 500, 1,
                     500, 2000, 2))

On the other hand, if you want to use the ggplot2 functions, the rasterVis package provides a simple wrapper around ggplot that works with RasterLayer objects:

library(rasterVis)

gplot(r) +
    geom_raster(aes(fill = factor(value))) +
    coord_equal()

to define your own colors you can add then:

scale_fill_manual(values=c('red','green')))

The best is indeed to modify the underlying data set by manually discretizing it. Below answer is based on the answer by joran.

library(ggplot2)
set.seed(1)
data <- data.frame(x     = rep(seq(1:10),times = 10), 
                   y     = rep(seq(1:10),each = 10),
                   value = runif(100,-10,10))

# Define category breaks
breaks <- c(-Inf,-3:3,Inf)
data$valueDiscr <- cut(data$value,
                       breaks = breaks,
                       right = FALSE)

# Define colors using the function also used by "scale_fill_gradient2"
discr_colors_fct <- 
  scales::div_gradient_pal(low = "darkred",
                           mid = "white", 
                           high = "midnightblue")
discr_colors <- discr_colors_fct(seq(0, 1, length.out = length(breaks)))
discr_colors
# [1] "#8B0000" "#B1503B" "#D18978" "#EBC3B9" "#FFFFFF" "#C8C0DB" "#9184B7" "#5B4C93" "#191970"

ggplot(data = data, aes(x=x,y=y)) +
  geom_raster(aes(fill = valueDiscr)) +
  coord_equal() +
  scale_fill_manual(values = discr_colors) +
  guides(fill = guide_legend(reverse=T))

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