R - Plotting a line with missing NA values

44,491

You could work with indices instead of na.omit(): something like this should do it:

plot(subset$Time[!is.na(subset$A)],subset$A[!is.na(subset$A)],type="l")  
# with your xlim and ylim, of course

lines(subset$Time,subset$B,type="p",col=27)
lines(subset$Time,subset$C,type="p",col=134)
Share:
44,491

Related videos on Youtube

panajach
Author by

panajach

Updated on February 09, 2020

Comments

  • panajach
    panajach over 4 years

    I have the following data.frame, "subset"

    Time            A   B   C
    2016-10-07 06:16:46 NA  NA  41 
    2016-10-07 06:26:27 40  39  42
    2016-10-07 06:38:23 NA  40  NA
    2016-10-07 06:41:06 42  42  44
    2016-10-07 06:41:06 NA  42  44
    2016-10-07 06:41:06 NA  42  44
    2016-10-07 06:41:07 44  43  48
    2016-10-07 06:41:41 NA  43  48
    2016-10-07 06:42:44 45  42  48
    2016-10-07 06:48:40 46  45  48
    

    I would like to have a plot where "Time" is the x-axis, "A" is a line and "B" and "C" are points.

    However, when i plot this, the only line that appears for "A" is the one connecting the last 2 dots (45 and 46), because these are the only 2 consecutive values in "A". The plot ignores the NAs between the values of "A" instead of potting a line connecting these values through the NAs. To do so, I use the following code:

    plot(subset$Time,subset$A,type="l",ylim=c(min(subset$B,na.rm=TRUE)-5,max(subset$C,na.rm=TRUE)+5),xlim=c(as.POSIXct(min(subset$Time)),as.POSIXct(max(subset$Time))))
    lines(subset$Time,subset$B,type="p",col=27)
    lines(subset$Time,subset$C,type="p",col=134)
    

    I have tried solutions such as na.omit() or na.approx(), however these seem to work only if I would plot "A" separately in a stand-alone plot, they do not seem to work in conjunction with "Time" and "B" and "C" all in the same plot.