代码之家  ›  专栏  ›  技术社区  ›  89_Simple

在ggplot中为每组插入垂直线

  •  0
  • 89_Simple  · 技术社区  · 7 年前
    dat <- data.frame(id = rep(1:4,each = 7), year = rep(2012:2018, times = 4),  
                  y = runif(28), start = rep(2012:2015,each = 7), end = rep(2014:2017,each = 7))
    
    ggplot(dat, aes(x = year, y = y)) + geom_line() + facet_wrap(~id) 
    

    如何为每个id插入两条垂直线,其位置由各自的起始列和结束列给出?

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  2
  •   joran    7 年前

    尝试以下操作:

    library(dplyr)
    library(tidyr)
    vlines <- dat %>% 
      select(id,start,end) %>% 
      distinct() %>% 
      gather(key = grp,value = x,start,end)
    
    ggplot(dat, aes(x = year, y = y)) + 
      geom_line() + 
      facet_wrap(~id) +
      geom_vline(data = vlines,aes(xintercept = x))