Draw Data Containing NA Values as Gaps in a ggplot2 geom_line Plot in R (Example Code)
In this tutorial you’ll learn how to draw data containing NA values as gaps in a ggplot2 line plot in R programming.
Creation of Example Data
my_df <- data.frame(col1 = 1:9, # Creating an example data frame col2 = c(4, 2, NA, NA, 5, 7, NA, 6, 3)) my_df # Printing the example data frame # col1 col2 # 1 1 4 # 2 2 2 # 3 3 NA # 4 4 NA # 5 5 5 # 6 6 7 # 7 7 NA # 8 8 6 # 9 9 3 |
my_df <- data.frame(col1 = 1:9, # Creating an example data frame col2 = c(4, 2, NA, NA, 5, 7, NA, 6, 3)) my_df # Printing the example data frame # col1 col2 # 1 1 4 # 2 2 2 # 3 3 NA # 4 4 NA # 5 5 5 # 6 6 7 # 7 7 NA # 8 8 6 # 9 9 3
Example: Creating a ggplot2 Line Graph with Gaps for Missing Values
install.packages("ggplot2") # Install & load ggplot2 library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 library("ggplot2")
ggplot(my_df, # Drawing ggplot2 plot with gaps aes(x = col1, y = col2)) + geom_line() |
ggplot(my_df, # Drawing ggplot2 plot with gaps aes(x = col1, y = col2)) + geom_line()
Related Tutorials
You may find some further R tutorials on topics such as ggplot2, regression models, and graphics in R below.