I would like to plot with gglot
's geom_raster
a 2D plot with 2 different gradients, but I do not know if there is a fast and elegant solution for this and I am stuck.
The effect that I would like to see is the overlay of multiple geom_raster
, essentially. Also, I would need a solution that scales to N different gradients; let me give an example with N=2 gradients which is easier to follow.
I first create a 100 x 100 grid of positions X and Y
# the domain are 100 points on each axis
domain = seq(0, 100, 1)
# the grid with the data
grid = expand.grid(domain, domain, stringsAsFactors = FALSE)
colnames(grid) = c('x', 'y')
Then I compute one value per grid point; imagine something stupid like this
grid$val = apply(grid, 1, function(w) { w['x'] * w['y'] }
I know how to plot this with a custom white to red gradient
ggplot(grid, aes(x = x, y = y)) +
geom_raster(aes(fill = val), interpolate = TRUE) +
scale_fill_gradient(
low = "white",
high = "red", aesthetics = 'fill')
But now imagine I have another value per grid point
grid$second_val = apply(grid, 1, function(w) { w['x'] * w['y'] + runif(1) }
Now, how do I plot a grid where each position "(x,y)" is coloured with an overlay of:
- 1 "white to red" gradient with value given by
val
- 1 "white to blue" gradient with value given by
second_val
Essentially, in most applications val
and second_val
will be two 2D density functions and I would like each gradient to represent the density value. I need two different colours to see the different distribution of the values.
I have seen this similar question but don't know how to use that answer in my case.