Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

r - Connecting across missing values with geom_line

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'd like a line to connect time 2 and 4 in that case. Is there a way to achieve this?

https://farm8.staticflickr.com/7061/6964089563_b150e0c2a6.jpg

I have a data frame of cumulative values like so:

head(cumulative)

  individual series Time     Value
1          A      x    1 -1.008821
2          A      x    2 -2.273712
3          A      x    3 -3.430610
4          A      x    4 -4.618860
5          A      x    5 -4.893075
6          A      x    6 -5.836532

Which I'm plotting with:

ggplot(cumulative, aes(x=Time,y=Value, shape=series)) + 
    geom_point() + 
    geom_line(aes(linetype=series)) + 
    facet_wrap(~ individual, ncol=3)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Richie's answer is very thorough, but I wanted to show something simpler. Since lines are not drawn to NA points, another approach is drop these points when drawing lines. This implicitly makes a linear interpolation between points (as straight lines do).

Using dfr from Richie's answer, without needing the calculation of z step:

ggplot(dfr, aes(x,y)) + 
  geom_point() +
  geom_line(data=dfr[!is.na(dfr$y),])

For that matter, in this case the subsetting could be done for the whole thing.

ggplot(dfr[!is.na(dfr$y),], aes(x,y)) + 
  geom_point() +
  geom_line()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...