繁体   English   中英

多行的每行一个线图(ggplot 或 base R?)

[英]One line plot per row for multiple rows (ggplot or base R?)

我有以下数据框:

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 标记可以是别的): 想要的情节

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

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

所以我用一个例子尝试了 base 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")

很明显,这些策略离期望的情节还有很长的路要走。 所以我的问题是如何最好地为单行制作所需的图,以及如何迭代它以保持前一行的点数?

非常感谢!

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)

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

在此处输入图片说明

编辑

使用 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)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM