Connecting across missing values with geom_line

后端 未结 2 955
盖世英雄少女心
盖世英雄少女心 2020-11-28 08:34

I\'m trying to figure out if it\'s possible to connect across missing values using geom_line. For example, in the link below there are missing values at time 3 in facet F. I

2条回答
  •  我在风中等你
    2020-11-28 09:11

    Lines aren't drawn if a value is NA. You need to replace these by interpolating across missing points. There are many different algorithms for interpolation, you need to experiment with several and see which one suits your data best. This example uses linear interpolation via interp1 in the pracma package.

    Sample data:

    dfr <- data.frame(
      x = 1:10,
      y = runif(10)
    )
    dfr[c(3, 6, 7), "y"] <- NA
    

    Interpolation step:

    dfr$z <- with(dfr, interp1(x, y, x, "linear"))
    

    Compare plots:

    ggplot(dfr, aes(x, y)) + geom_line()
    ggplot(dfr, aes(x, z)) + geom_line()
    

    If you are showing this graph to other people, make sure that you clearly mark the places where you've synthesised data by interpolating (maybe using dotted lines).


    Update based on comment:
    You can specify different aesthetics for different geoms.

    ggplot(dfr, aes(x)) + 
      geom_point(aes(y = y)) +
      geom_line(aes(y = z))
    

    To incorporate different line types for missing/non-missing y, you can do something like

    ggplot(dfr, aes(x)) + 
      geom_point(aes(y = y)) +
      geom_line(aes(y = y)) +
      geom_line(aes(y = z), linetype = "dotted")
    

提交回复
热议问题