This code produces the first plot below:
water.height <- seq(0, 5, 1)
y <- seq(0, 1500, length.out = 6)
df <- data.frame(water.height, y)
library(g
I used Kamil Slowikowski's example to build a simpler function that generates linear gradients depending on a series of values. This can be of use if you have a relationship of some kind between three variables (eg. y~x*z where z also varies over x). Then you just plot y~x and have z~x as a color gradient in the background.
water.height <- seq(0, 5, 1)
y <- seq(0, 1500, length.out = 6)
z <- rnorm(6, 10, 1)
df <- data.frame(water.height, y, z)
grad_by_val <- function(x, y, cols = blues9) {
require(grid)
y <- y[order(x)]
ys <- (y - min(y)) / diff(range(y))
cols <- colorRamp(cols)(ys) / 256
colnames(cols) <- c("red", "green", "blue")
cols <- apply(cols, 1, function(z) do.call(rgb, as.list(z)))
mat <- matrix(cols, ncol = length(x))
rasterGrob(
image = mat,
width = unit(1, "npc"),
height = unit(1, "npc"),
interpolate = TRUE
)
}
library(ggplot2)
ggplot(df, aes(water.height, y)) + geom_blank() + theme_bw() +
annotation_custom(
grob = grad_by_val(df$water.height, df$z),
xmin = -Inf,
xmax = Inf,
ymin = -Inf,
ymax = Inf
) +
geom_point(
size = 5,
color = "#FFFFFF",
fill = "#000000",
shape = 21
)
To add a legend see here.