Plot background colour in gradient

后端 未结 3 939
我寻月下人不归
我寻月下人不归 2020-12-01 21:24

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         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 22:04

    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.

提交回复
热议问题