Question

Remove gap in line plot in R

Please help me plot a single line that changes from solid (measured) to dashed (estimate) after year 2008 and has a legend respectively. My code:

    date<-as.POSIXct(c("1981-01-01","2008-01-01", "2024-01-01", "2050-01-01"), format = "%Y-%m-%d", tz=Sys.timezone())
    sed_pool_vol<-as.numeric(c(0, 938, 1493, 2397 ))
    group<- c("measured", "measured", "estimate", "estimate")
    sed_df<-data.frame(date, sed_pool_vol,group)


ggplot(sed_df, aes(x = date, y = sed_pool_vol,linetype = group)) +
  geom_line()+
  scale_linetype_manual("group",values=c("estimate"=2,"measured"=1))

Resulting Plot

 2  29  2
1 Jan 1970

Solution

 3

Simplest approach might be to use a different geom: (assuming dplyr is loaded)

geom_segment(aes(xend = lead(date), yend = lead(sed_pool_vol))) +

enter image description here

Other approaches that might be useful in similar circumstances could be to copy the transition point so that each series could be plotted separately using geom_line, or to use one of the geoms in ggforce which allow you more flexibility to change characteristics along the length of a series.

2024-07-22
Jon Spring