panajach
panajach

Reputation: 115

R - Plotting a line with missing NA values

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.

Upvotes: 3

Views: 58503

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269596

Try this:

xlim <- range(subset$Time)
ylim <- range(subset[-1], na.rm = TRUE)
plot(A ~ Time, na.omit(subset[1:2]), type = "l", xlim = xlim, ylim = ylim)
points(B ~ Time, subset, col = 27)
points(C ~ Time, subset, col = 134)

Another possibility is to use the subset= argument of plot in which case we replace the plot line above with:

ok <- ! is.na(subset$A)
plot(A ~ Time, subset, subset = ok, type = "l", xlim = xlim, ylim = ylim)

In either case we get this graphic:

screenshot

Upvotes: 0

Matt Tyers
Matt Tyers

Reputation: 2215

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)

Upvotes: 5

Related Questions