Adding a geom_line to all facets in a facet_wrap plot in R

后端 未结 2 1913
失恋的感觉
失恋的感觉 2021-02-05 14:44

I\'m trying to create a facet_wrap plot that compares four separate lines to a common fifth line; the goal is to have this fifth line appearing on all four of the o

相关标签:
2条回答
  • 2021-02-05 15:02

    You could also use geom_abline(...) as follows:

    x    <-  c( 1,  3,  1,  3,  2,  4,  2,  4)
    y    <-  c( 1,  3,  2,  4,  1,  3,  2,  4)
    type <-  c("A","A","B","B","C","C","D","D")
    data <-  data.frame(x,y,type)
    
    int   <- c(5,5,5,5)
    slope <- c(-1,-1,-1,-1)
    type  <- c("A","B","C","D")
    ref   <- data.frame(int, slope, type)
    ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type, scales="free") +
      geom_abline(data = ref, aes(intercept=int, slope=slope), color="red", size=2)
    

    Which produces this:

    0 讨论(0)
  • 2021-02-05 15:08

    You have specified type='E' in your line data.frame. If you want to have this line on type A,B,C,D, then create a data.frame with the types on which you want the line to display

    xl    = c( 4,  1)
    yl    = c( 1,  4)
    type =rep(LETTERS[1:4], each=2)
    line2 = data.frame(x=xl,y=yl,type)
    
    ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
       geom_line(data = line2)
    

    You could also use annotate, which means you don't specify a data.frame, but pass the x and y values directly

    ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
      annotate(geom='line', x=xl,y=yl)
    

    Both create

    enter image description here

    0 讨论(0)
提交回复
热议问题