basil basil - 17 days ago 9
R Question

R - ggplot2 - use raster as greyscale basemap

I have two raster layers, one is a greyscale image and the other results from an analysis. I'd like to use one raster as greyscale background in ggplot and superimpose the second raster using a color-ramp. This is an example how it could look like (but nicer):

enter image description here

I can't assign separate colors to the rasters. Do you know a way to achieve this? I googled for a long time and I have the impression that this is not possible. But I can't (and don't want to) belive it.

Please let me know if you need further infomrmation.

Example

create test data

xy.1 <- expand.grid(1:10, 1:10)
df.1 <- data.frame(Longitude=xy.1[,1], Latitude=xy.1[,2], Value=xy.1[,1]+xy.1[,2])
xy.2 <- expand.grid(3:5, 3:5)
df.2 <- data.frame(Longitude=xy.2[,1], Latitude=xy.2[,2], Value=rnorm(9))


plot

p1 <- ggplot() +
geom_raster(data=df.1, aes(x=Longitude, y=Latitude, fill=Value)) +
scale_fill_gradientn(colours = grey(seq(0,1,l=20))) +
coord_equal() +
theme(legend.position="none")

p1 + geom_raster(data=df.2, aes(x=Longitude, y=Latitude, fill=Value)) +
scale_fill_gradient(low="red", high="white")


Result:

enter image description here

Answer

I wrote a function that allows to add a background and superimpose a foreground raster using ggplot2.

Edit: I added a better solution at the end

This is how it works:

I combine the two rasters and shift the values, such that the values do not overlap. Then, I plot the raster layer with a scalebar containing the color scale for foreground (e.g. red -> green), where the background color scale is hard-coded (black -> white). There is no limit in the number of colors.

The legend of the raster layer is not displayed. To get a legend that does not contain the whole scale-bar (that would be black -> white -> red -> green), I insert two dummy-points in the background. One with the smallest value of the foreground data, one with the largest. This gives a legend only for the foreground data.

If someone knows a nicer way to do the scaling and creating the color-scale, I would be happy to add this to the function.

I added the possibility to scale the foreground data using quantiles; The argument fg.quant takes a vector of two integers, used for "cutting" the data. bw.scale allows to make the background raster darker / brighter: bw.scale=c(0, 0.5) means that the background image has a color scale from black to grey(0.5), for example.

I know that this is not a perfect function. But it is very useful for me and I will improve it and try to eliminate the ugly parts once I have some free time.

test data

# 'background'
r.1 <- raster(x=matrix(rowSums(expand.grid(1:10, 1:10)), nrow=10),
              xmn=0, xmx=10, ymn=0, ymx=10)
# 'foreground'
r.2 <- raster(x=matrix(rnorm(16), nrow=4),
              xmn=3, xmx=7, ymn=3, ymx=7)

plot function

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# BGPlot() -- plot data with background raster using ggplot2
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

BGPlot <- function(fg,
                   bg,
                   cols=c('red', 'green'),
                   fg.quant=c(0, 1),
                   bw.scale=c(0, 1),
                   plot.title='',
                   leg.name='Value') {
  # plot data with background raster using ggplot2
  #
  # Args
  #   fg: foreground raster layer
  #   bg: background raster layer
  #   cols: colors to use for fg
  #   fg.quant: scaling fg by quantiles
  #   bw.scale: makes bg darker / brighter:
  #     E.g. c(0, 0.9) -> darker / c(0.2, 1) -> brighter
  #   plot.title: title
  #   leg.name: name to be displyed at legend
  #
  # Returns
  #   ggplot object

  # load libraries
  library(ggplot2)

  # get min / max of foreground raster
  fg.q <- quantile(fg, fg.quant)
  fg.min <- fg.q[1]
  fg.max <- fg.q[2]

  # rescale fg
  fg.sc <- (fg-fg.q[1]) / (fg.q[2]-fg.q[1])
  fg.sc[fg.sc<0] <- 0
  fg.sc[fg.sc>1] <- 1
  fg.sc <- fg.sc + 0.1

  # get scale (fg values 0.1, 10, 1000 range?)
  ifelse((fg.max-fg.min)/10>=1, n.dgts <- 0, n.dgts <- 1)

  # create fg legend breaks / labels
  fg.breaks <- round(seq(fg.min, fg.max, l=5), n.dgts)
  fg.breaks[1] <- ceiling(fg.min*(10^n.dgts))/(10^n.dgts)
  fg.breaks[5] <- floor(fg.max*(10^n.dgts))/(10^n.dgts)

  fg.labs <- paste0(c(paste0(round(fg.min, n.dgts+1), '-'),'','','',''),
                    fg.breaks,
                    c('','','','',paste0('-', round(fg.max, n.dgts+1)))
  )


  # rescale bg
  bg.sc <- (bg-minValue(bg)) /
    (maxValue(bg)-minValue(bg)) *
    (bw.scale[2]-bw.scale[1]) + bw.scale[1] -1.1


  # merge rasters, fg over bg
  r <- merge(fg.sc, bg.sc)

  # convert raster to data.frame
  r.df <- as.data.frame(rasterToPoints(r))
  names(r.df) <- c('Longitude', 'Latitude', 'Value')

  # get center of r
  mid.Lon <- mean(r.df$Longitude)
  mid.Lat <- mean(r.df$Latitude)

  # set scale positions
  vals <-c(-1.1,-0.1, seq(0.1,1.1,l=length(cols)))

  # set dummy-point values
  dp <-seq(fg.min,fg.max,l=length(cols))


  # plotting; 
  p <-
    ggplot() +
    # dummy points: points not visible, needed to display custom scale-bar
    geom_point(data=data.frame(x = rep(mid.Lon, length(cols)),
                               y = rep(mid.Lat, length(cols)),
                               c = dp),
               aes(x, y, color=c)) +
    scale_color_gradientn(colours = cols,
                          breaks=fg.breaks,
                          labels=fg.labs,
                          name=leg.name) +
    # raster; no scale-bar plotted
    geom_raster(data=r.df, aes(x=Longitude, y=Latitude, fill=Value)) +
    scale_fill_gradientn(colours  = c('black', 'white', cols),
                         values   = vals,
                         rescaler = function(x,...) x,
                         oob      = identity,
                         guide    = "none") +
    ggtitle(label=plot.title) +
    theme_light() +
    labs(list(x='Lon', y='Lat')) +
    theme(axis.text.y=element_text(angle=90, hjust=0.5)) +
    coord_equal()

  return(p)
}

function call

BGPlot(fg=r.2, bg=r.1, cols=c('red', 'green'), fg.quant=c(0.01, 0.99), bw.scale=c(0, 0.8), plot.title='Chlorophyll Concentration', leg.name='CHL')

enter image description here

A "real-world" example:

enter image description here

EDIT: Better solution using R package 'RStoolbox'

This is a very easy and perfect working solution using the package RStoolbox. The function ggR produces a greyscale background image, function ggRGB an RGB background.

library(ggplot2)
library(RStoolbox)
ggR(BACKGROUND_IMAGE, geom_raster=FALSE) +
geom_raster(...) # here comes standard raster plot