Reuben Mathew
Reuben Mathew

Reputation: 598

ggplot2 geom_line() to skip NA values

I have a data set that has multiple NA values in it. When plotting this data, ggplot's geom_line() option joins lines across the NA values. Is there any way to have ggplot skip joining the lines across NA values?

Edit: A thousand apologies to all involved. I made a mistake in my manipulation of the data frame. I figured out my problem. My x axis was not continuous when I created a subset. The missing data had not been replaced by NAs, so the data was being linked because there were no NAs created in the subset between rows.

Upvotes: 7

Views: 11159

Answers (1)

Drew Steen
Drew Steen

Reputation: 16607

geom_line does make breaks for NAs in the y column, but it joins across NA values in the x column.

# Set up a data frame with NAs in the 'x' column
independant <- c(0, 1, NA, 3, 4)
dependant <- 0:4
d <- data.frame(independant=independant, dependant=dependant)

# Note the unbroken line
ggplot(d, aes(x=independant, y=dependant)) + geom_line()

enter image description here

I assume that your NA values are in your as.POSIXlt(date). If so, one solution would be to map the columns with NA values to y, and then use coord_flip to make the y axis horizontal:

ggplot(d, aes(x=dependant, y=independant)) + geom_line() +
  coord_flip()

enter image description here

Presumably your code would be:

ggplot(crew.twelves, aes(x=laffcu, y=as.POSIXlt(date)) + geom_line() +
  coord_flip()

Upvotes: 16

Related Questions