我正在尝试用一些阴影矩形绘制一些数据。
数据框 df
如下所示:
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"))
对于图中的矩形,我使用变量 xmin
和 xmax
定义了一个名为 dfRect
的对象。
dfRect <- data.frame(xmin = c(0.3, 1.0, 1.9), xmax = c(0.7, 1.5, 2.0))
问题是我必须为矩形的开始和结束手动找到 xmin
和 xmax
。一个矩形在 type
列中 b
的时间序列的开始处开始 (xmin
),并在同一时间序列的结束处结束b
。单个 b
可以忽略。
这是情节,因此您可以了解我要完成的工作:
ggplot() +
geom_rect(data = dfRect,
aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf),
fill = "yellow", alpha = 0.4) +
geom_line(data = df, aes(x = time, y = speed, color = type, group = 1), size = 3)
所以最后的问题是。如何自动化定义 xmin
和 xmax
的过程并自动创建 dfRect,这样我就不必自己定义它了?
最佳答案
这是一种使用游程编码的方法。
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)
要得到你想要的,你需要过滤掉 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)
如果您正在寻找可以为您计算的统计数据,请查看 here .免责声明:我编写了这个函数,它的作用与我上面发布的代码类似。
关于r - 如何在R中为ggplot中的矩形自动查找序列的开始和结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62501914/