r - 如何在R中为ggplot中的矩形自动查找序列的开始和结束

标签 r ggplot2 plot rectangles

我正在尝试用一些阴影矩形绘制一些数据。

数据框 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"))

对于图中的矩形,我使用变量 xminxmax 定义了一个名为 dfRect 的对象。

dfRect <- data.frame(xmin = c(0.3, 1.0, 1.9), xmax = c(0.7, 1.5, 2.0))

问题是我必须为矩形的开始和结束手动找到 xminxmax。一个矩形在 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)

所以最后的问题是。如何自动化定义 xminxmax 的过程并自动创建 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)

要得到你想要的,你需要过滤掉 FALSEs。


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/

相关文章:

r - 如何在 r 中的两个变量中保留具有相同值的行?

r - 在 R 中创建高分辨率图形

user-interface - 在 Matlab 中将绘图保存为 JPEG 文件

r - 如何在 R ggpolot2 plot 中向 xaxis 添加额外的离散点?

r - 使用函数通过查找列表完成不完全链接的文档(文档树)

R:删除文本中的点但不删除标记小数点的点

r - 将 geom_smooth 与变换后的 y 一起使用

r - 生存曲线中多组的不同颜色类型和线型

r - 带有 ggplot2 for R 的多色标题

r - 增加类型 "h"R 图的宽度