Angus
Angus

Reputation: 355

ggplot two lines on same chart from data with different number of rows

I'm always having this problem where I need to plot two lines on a chart, but there are different number of rows in my data. I keep getting this error and I wish I could solve it once and for all:

Error: (converted from warning) Removed 5 row(s) containing missing values (geom_path).

Here is some sample data (I didn't manually add the NAs):

datamre <- structure(list(xR = c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 
23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, NA, NA, NA, NA), received = c(0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.1666667, 0.1666667, 0.1666667, 
0.1666667, 0.1666667, 0.1666667, 0.1666667, 0.1666667, 0.1666667, 
0.1666667, 0.1666667, 0.1666667, 0.1666667, 0.1666667, 0.1666667, 
0.1666667, 0.1666667, 0.1666667, 0.1666667, 0.1666667, NA, NA, 
NA, NA), xD = 0:34, demand = c(0, 0.08333333, 0.08333333, 0.08333333, 
0.08333333, 0.08333333, 0.08333333, 0.08333333, 0.16666667, 0.25, 
0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 
0.25, 0.25, 0.25, 0.25, 0.33333333, 0.33333333, 0.33333333, 0.33333333, 
0.33333333, 0.33333333, 0.33333333, 0.41666667, 0.41666667, 0.41666667
)), row.names = c(NA, 35L), class = "data.frame")

And the simple code I'm using:

df <- data.frame(datamre)
ggplot(df) +
   geom_line(aes(xR,received)) +
   geom_line(aes(xD,demand)) 

Upvotes: 1

Views: 127

Answers (1)

Mohanasundaram
Mohanasundaram

Reputation: 2949

Try this:

ggplot(df[complete.cases(df),]) +
  geom_line(aes(xR,received)) +
  geom_line(aes(xD,demand))

Upvotes: 1

Related Questions