Search code examples
rggplot2line

Is there a way to connect only certain points with a line in ggplot2?


Is there a way to connect only certain points with a line in ggplot2? For example, if I have a simple scatter plot with an x axis ranging from 0 to 20, but I only want points to be connect by a line when the x value is 5 to 20, thus points that range from 0 to 5 are excluded and not connected by a line.


Solution

  • Modify the data or aes passed into geom_line. Here I make a smaller dataframe containing only the points I want connected by a line. You can also subset in-place.

    df <- data.frame(x = 0:20, y = 0:20)
    line.df <- df[df$x > 5, ]
    ggplot(df, aes(x=x, y=y)) + 
      geom_point() + 
      geom_line(data = line.df) 
    

    enter image description here