То, что вы искали, было на самом деле ниже в ответах на пост, который вы связали. Это функция grad_by_val()
из ответа jkd .
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)
Вывод: