每行一行多行(ggplot或base R?)

时间:2017-10-27 22:21:50

标签: r plot ggplot2

我有以下数据框:

test_new <- structure(list(PS_position = c(12871487, 12997222, 12861487, 
 12871491, 12934355), Region_ID = structure(c(1L, 1L, 2L, 2L, 
 1L), .Label = c("D", "D_left", "D_right"), class = "factor"), 
 chr_key = c(1, 1, 1, 1, 1), start = c(12871487, 12871487, 
 12871487, 12871487, 12871487), stop = c(12997222, 12997222, 
 12997222, 12997222, 12997222), exact_center = c(12934355, 
 12934355, 12934355, 12934355, 12934355)), .Names = c("PS_position", 
 "Region_ID", "chr_key", "start", "stop", "exact_center"), row.names = c(1L, 
 2L, 3L, 4L, 7L), class = "data.frame")

我想为每一行制作一个情节,其中每个区域的开始,停止和中心保持不变,并且逐个添加PS_position作为一个点,如下所示(字母不需要在图中出现)并且PS_position标记可以是其他任何东西): desired plot

这在ggplot中很难做到geom_vline()和geom_hline():

ggplot(test_new) + geom_vline(xintercept = 12871487) + geom_vline(xintercept = 12997222) + geom_vline(xintercept = 12934355)

所以我试着用R作为例子:

plot(1,1)
lines(c(0.8, 1.2), c(0.6, 0.6))
abline(v = 1, col = "gray60")
abline(v=1.2, col = "gray60")
abline(v=0.8, col = "gray60")

很明显,这些策略距离所需的情节还有很长的路要走。所以我的问题是如何最好地为单个行创建所需的绘图,以及如何迭代它以保留前一行中的点的更多行?

非常感谢!

1 个答案:

答案 0 :(得分:1)

Reduce(
  function(plot, position) {
    plot + annotate(
      geom = "point", 
      x = position, y = 1, 
      shape = 18, size = 5)
  }, 
  test_new$PS_position, 
  init = ggplot() + 
    theme_minimal() +
    theme(
      panel.grid =element_blank(),
      axis.text = element_blank(),
      axis.line = element_blank()) +
    labs(x = NULL, y = NULL) +
    geom_vline(xintercept = c(12871487, 12934355, 12997222), color = "red"),
  accumulate = TRUE)

将构建一个包含迭代添加点的图表列表,看起来非常接近您的想法,最后一个情节看起来像这样

enter image description here

修改

使用dplyr,tidyr和purrr按数据框分组。这只是按Region_ID进行分组,为列

中的每个数据帧嵌套并运行相同的减少量
library(dplyr)
library(purrr)
library(tidyr)

test_new %>%
  group_by(Region_ID) %>%
  nest() %>%
  mutate(plots = map(data, ~Reduce(
    function(plot, position) {
      plot + annotate(
        geom = "point", 
        x = position, y = 1, 
        shape = 18, size = 5)
    }, 
    .$PS_position, 
    init = ggplot() + 
      theme_minimal() +
      theme(
        panel.grid =element_blank(),
        axis.text = element_blank(),
        axis.line = element_blank()) +
      labs(x = NULL, y = NULL) +
      geom_vline(xintercept = c(12871487, 12934355, 12997222), color = "red"),
    accumulate = TRUE)))