Avoid Gap in ggplot2 Line Plot with NA Values in R (Example Code)

This page illustrates how to connect the lines in a line plot with missing values in the R programming language.

Setting up the Example

data(iris)                                         # Loading & preparing a data set
iris_NA <- iris[ , c(1, 5)]
iris_NA$Sepal.Length[c(1, 4, 5, 8:15, 50:55, 70:80, 120:140)] <- NA
iris_NA$count <- 1:50
head(iris_NA)
#   Sepal.Length Species count
# 1           NA  setosa     1
# 2          4.9  setosa     2
# 3          4.7  setosa     3
# 4           NA  setosa     4
# 5           NA  setosa     5
# 6          5.4  setosa     6
install.packages("ggplot2")                        # Install ggplot2 package
library("ggplot2")                                 # Load ggplot2
ggplot(iris_NA,                                    # Drawing ggplot2 plot of all data
       aes(x = count,
           y = Sepal.Length,
           col = Species)) +
  geom_line()

r graph figure 1 avoid gap ggplot2 line na values r

Example: How to Connect Lines in ggplot2 Line Graph with Missing Values

ggplot(iris_NA[!is.na(iris_NA$Sepal.Length), ],    # Using only observed cases to draw plot
       aes(x = count,
           y = Sepal.Length,
           col = Species)) +
  geom_line()

r graph figure 2 avoid gap ggplot2 line na values r

Related Articles & Further Resources

Please find some additional R tutorials on topics such as plot legends, graphics in R, and regression models below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top