用不同的x值填充两行之间的区域

利安德

我有一个带有两列x和y的数据框。每行表示一行,并且在每个单元格中是具有51个连续观察值的列表(因此,每行中有2个针对x和y的列表)。

我想填充数据框中的行之间的空间。

问题在于x和y中存在随机性,因此我不能仅对x上的每个数据点取ymin和ymax。

此代码将创建与我的实际数据集相似的样本数据(每行只有2行,每行10个观察值):

library(data.table)

genData <- function() {
  set.seed(42)
  genOneLine <- function(m_x, m_y) {
    xs = seq(0,1,by=0.1)
    x_ran <- rnorm(8, m_x, 0.1)
    xs[2:9] = xs[2:9] + x_ran
    ys = seq(0,1,by=0.1)
    y_ran <- rnorm(8, m_y, 0.1)
    ys[2:9] = ys[2:9] + y_ran
    return (data.table(x = list(xs), y = list(ys)))
  }
  return (rbind(genOneLine(-0.1, -0.1), genOneLine(0.1, 0.1)))
}
林正

看看这是您的想法吗?

library(dplyr)
library(ggplot2)
library(data.table)

df <- genData()

df %>%

  # add identifier variable to each line
  mutate(id = seq(1, n())) %>%

  # make each element of the list its own row
  tidyr::unnest() %>%

  # add sequence identifier, from start of line 1 to its end, then
  # from the end of line 2 to its start
  group_by(id) %>%
  mutate(order = ifelse(id == 1, seq(1, n()), n() + seq(n(), 1))) %>%
  ungroup() %>%

  # sort data frame
  arrange(order) %>%

  # plot
  ggplot(aes(x = x, y = y)) +
  geom_polygon(aes(group = 1), fill = "grey20", alpha = 0.5) +
  geom_path(aes(color = factor(id)), size = 2)

结果

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章