将连续变量绘制为背景ggplot2中的颜色渐变

问题描述 投票:0回答:1

我有一个关于海洋环境温度的数据集,看起来像这样:

日期时间戳SW2017/11/1上午02:00:00 17.88042017/11/1上午04:00:00 17.81062017/11/1上午06:00:00 17.7522017/11/1上午08:00:00 17.73152017/11/1上午10:00:00 17.90662017/11/1下午12:00:00 18.12292017/11/1下午02:00:00 18.55512017/11/1下午04:00:00 19.27192017/11/1下午06:00:00 18.61022017/11/1下午08:00:00 18.08092017/11/1下午10:00:00 17.99752017/11/2上午02:00:00 17.65662017/11/2上午04:00:00 17.42342017/11/2上午06:00:00 17.60842017/11/2上午08:00:00 17.5954...

我想在另一个ggplot2图的背景中以温度作为颜色梯度,显示同一时间段内的增长率,以寻找温度和增长率这两个变量之间的相关性。这里提出了一个类似的问题:Plot background colour in gradient,但是我还没有弄清楚如何使用连续变量为渐变编码。

非常感谢

r ggplot2 colors gradient
1个回答
0
投票

您正在寻找的内容实际上在您所链接的帖子的答案中更靠后。这是grad_by_val()中的jkd's answer功能。

library(ggplot2)

# Load your data
dat <- "Date, SW
11/1/2017 02:00:00 AM, 17.8804
11/1/2017 04:00:00 AM, 17.8106
11/1/2017 06:00:00 AM, 17.752
11/1/2017 08:00:00 AM, 17.7315
11/1/2017 10:00:00 AM, 17.9066
11/1/2017 12:00:00 PM, 18.1229
11/1/2017 02:00:00 PM, 18.5551
11/1/2017 04:00:00 PM, 19.2719
11/1/2017 06:00:00 PM, 18.6102
11/1/2017 08:00:00 PM, 18.0809
11/1/2017 10:00:00 PM, 17.9975
11/2/2017 02:00:00 AM, 17.6566
11/2/2017 04:00:00 AM, 17.4234
11/2/2017 06:00:00 AM, 17.6084
11/2/2017 08:00:00 AM, 17.5954"
dat <- read.table(text = dat, header = T, sep = ",", as.is = T)
# convert to date format
dat$Date <- as.POSIXct(dat$Date, format = "%m/%d/%Y %I:%M:%S %p")

# function from jkd's post
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
  )
}

根据您的数据,得出:

ggplot(dat, aes(x = Date, y = SW)) +      
  annotation_custom(
    grob = grad_by_val(dat$Date, dat$SW, cols = heat.colors(10)),
    xmin = -Inf,
    xmax = Inf,
    ymin = -Inf,
    ymax = Inf) +
  geom_point() # make sure you plot stuff AFTER the gradient (or it'll be below it)

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.