有没有一种更干净的方法将文本/标签添加到多条垂直线:geom_vline()?

时间:2019-04-23 20:49:54

标签: r ggplot2 label

我想在图的顶部添加手动标签以定义垂直线。每个“面板”代表一条染色体。

我的情节:

plot

在使用geom_vline()之前,我尝试过使用facet_grid(),并且标签是完美的,但是即使使用scales = "free_xspace = "free_x",X轴也不与染色体长度成比例。参数(有关其他详细信息/代码/图的链接,请参见previous post

facet_grid作图:

plot 2

现在,我想手动添加标签,使其外观类似于facet_grid面板标签。

我尝试过使用annotategeom_text,而我最好的主意是对每个面板标签使用自己的代码行(?)和现在的代码使用geom_text正在消耗内存/无法正常工作。

可以在Plotting coverage depth in 1kb windows?上找到生成基本图的代码。

要添加面板标签:

label.plot <- Xdepth.average.plot +
  geom_text(aes(x=115109, y=200, label="I"), colour="black") +
  geom_text(aes(x=636810, y=200, label="II"), colour="black") +
  geom_text(aes(x=1201712, y=200, label="III"), colour="black") +
  geom_text(aes(x=2125989, y=200, label="IV"), colour="black") +
  geom_text(aes(x=3180392, y=200, label="V"), colour="black") +
  geom_text(aes(x=3603910, y=200, label="VI"), colour="black") +
  geom_text(aes(x=4284460, y=200, label="VII"), colour="black") +
  geom_text(aes(x=5111252, y=200, label="VIII"), colour="black") +
  geom_text(aes(x=5612517, y=200, label="IX"), colour="black") +
  geom_text(aes(x=6205337, y=200, label="X"), colour="black") +
  geom_text(aes(x=6911620, y=200, label="XI"), colour="black") +
  geom_text(aes(x=7784117, y=200, label="XII"), colour="black") +
  geom_text(aes(x=8785421, y=200, label="XIII"), colour="black") +
  geom_text(aes(x=9639803, y=200, label="XIV"), colour="black") +
  geom_text(aes(x=10577615, y=200, label="XV"), colour="black") +
  geom_text(aes(x=11597293, y=200, label="XVI"), colour="black")
label.plot

1 个答案:

答案 0 :(得分:0)

应该有可能使用基于单个表的几个几何来复制该格式,该表包含您关心的坐标。例如,如果您具有垂直线应到达的位置的列表,则可以使用它来生成直线,矩形和文本。

library(tidyverse)

df <- tribble(     ~x,   ~y, ~label,
               115109,  200, "I",
               636810,  200, "II",
              1201712,  200, "III",
              2125989,  200, "IV",
              3180392,  200, "V",
              3603910,  200, "VI",
              4284460,  200, "VII",
              5111252,  200, "VIII",
              5612517,  200, "IX",
              6205337,  200, "X",
              6911620,  200, "XI",
              7784117,  200, "XII",
              8785421,  200, "XIII",
              9639803,  200, "XIV",
              10577615, 200, "XV",
              11597293, 200, "XVI",
              12597293, 200, "") # added to give end point for XVI

ggplot(df) +
  geom_segment(aes(x = x, xend = x,
                   y = 0, yend = 200)) +
  geom_rect(aes(xmin = x, xmax = lead(x),
                ymin = y - 10, ymax = y + 10),
            fill = "gray70", color = "black") +
  geom_text(aes(x = (x + lead(x))/2,
                y = y, label = label)) +
  coord_cartesian(ylim = c(0, 230))

enter image description here