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

时间:2018-11-13 20:18:41

标签: r ggplot2 plot

我有一个带有两列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)))
}

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)

result