Search code examples
rggplot2missing-dataline-plot

ggplot2 fill gaps by joining a line and no symbol


I would like to have a chart that connects missing points by a line, but not show a symbol at the missing point. Here is some code that creates some test data and produces a chart, but I would like a (id=B) green line joining points 4 and 6 with a straight line, but no green triangle at time 5. I did try geom_path instead of geom_line, but nothing much changed. Thanks

library(ggplot2)

set.seed(1)
x <- rep(seq(1:10), 3)
y <- c(runif(10), runif(10) + 1, runif(10) + 2)
group <- c(rep("A", 10), rep("B", 10), rep("C", 10))

df <- data.frame(cbind(group, x, y))
df$x <- as.numeric(df$x)
df$y <- as.numeric(df$y)
df[15,]$y <- NA

ggplot(data=df, aes(x=x, y=y, group=group)) +
  geom_line(aes(colour=group))+
  geom_point(aes(colour=group, shape=group))+
  scale_shape_manual(values = c(1:3)) +
  theme(legend.position="bottom")

Solution

  • You can do this by removing rows where y is NA:

    df2 <- df[!is.na(df$y), ]
    
    ggplot(data=df2, aes(x=x, y=y, group=group)) +
      geom_line(aes(colour=group))+
      geom_point(aes(colour=group, shape=group))+
      scale_shape_manual(values = c(1:3)) +
      theme(legend.position="bottom")