Вот подход с использованием кодирования длин серий.
library(ggplot2)
df <- data.frame(time = seq(0.1, 2, 0.1),
speed = c(seq(0.5, 5, 0.5), seq(5, 0.5, -0.5)),
type = c("a", "a", "b", "b", "b", "b", "c", "c", "c", "b", "b", "b", "b", "b", "c", "a", "b", "c", "b", "b"))
# Convert to runlength encoding
rle <- rle(df$type == "b")
# Ignoring the single "b"s
rle$values[rle$lengths == 1 & rle$values] <- FALSE
# Determine starts and ends
starts <- {ends <- cumsum(rle$lengths)} - rle$lengths + 1
# Build a data.frame from the rle
dfrect <- data.frame(
xmin = df$time[starts],
# We have to +1 the ends, because the linepieces end at the next datapoint
# Though we should not index out-of-bounds, so we need to cap at the last end
xmax = df$time[pmin(ends + 1, max(ends))],
fill = rle$values
)
Этот график дает представление о том, что мы делали в приведенном выше коде:
ggplot() +
geom_rect(data = dfrect,
aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf, fill = fill),
alpha = 0.4) +
geom_line(data = df, aes(x = time, y = speed, color = type, group = 1), size = 3)
To get what you want you'd need to filter out the FALSE
s.
ggplot() +
geom_rect(data = dfrect[dfrect$fill,],
aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf),
alpha = 0.4, fill = "yellow") +
geom_line(data = df, aes(x = time, y = speed, color = type, group = 1), size = 3)
If you are looking for a stat that can calculate this for you, have a look здесь . Отказ от ответственности: я написал эту функцию, которая делает то же самое, что и код, который я опубликовал выше.