'ggplot multiple line charts with reshape2 melt() - ignoring NA/empty in the chart

I am trying to plot a Milestone Trend Analysis with R. At some point, a Milestone is reached and will not be reported anymore. That's also when the line in the graph should stop. So I tried to implement this with ggplot and reshape2 to melt the dataset in a long format:

#edit (Data model by code, sorry) Datamodel: Datamodel "MTA_data"

MTA_data<- data.frame(ReportingDates = c("01.01.2021", "01.02.2021", 
                                          "01.03.2021", "01.04.2021", "01.05.2021", "01.06.2021", "01.07.2021", 
                                          "01.08.2021", "01.09.2021", "01.10.2021", "01.11.2021", "01.12.2021"),
                       Milestone1 = c("01.02.2021", "01.03.2021", NA, NA, NA, NA,NA, NA, NA, NA, NA, NA),
                       Milestone2 = c("01.06.2021", "01.06.2021","01.06.2021", "01.06.2021", "01.07.2021",
                                      "01.07.2021", NA, NA,NA, NA, NA, NA),
                       Milestone3 = c("01.09.2021", "01.09.2021", "01.09.2021", "01.09.2021", "01.09.2021",
                                      "01.09.2021", "01.09.2021", "01.11.2021", "01.11.2021", "01.11.2021",
                                      "01.11.2021", NA),
                       MilestoneDates = c("01.01.2021","01.02.2021", "01.03.2021", "01.04.2021", "01.05.2021", "01.06.2021",
                                          "01.07.2021", "01.08.2021", "01.09.2021", "01.10.2021", "01.11.2021","01.12.2021"))

dput(MTA_data)

#code for meld and plot:

MTA_data.long <-melt(MTA_data,id.vars = "ReportingDates")
x <- ggplot(MTA_data.long, aes(ReportingDates,value,color=variable))+
              geom_line(data=MTA_data.long, aes(x=ReportingDates, y=value, group=variable))+
              geom_point()

x

result: ggplot chart with N/A

Well, since some milestones don't have a planning date anymore at some reporting date (milestone is reached), the value is NA or empty (doesn't matter, the issue remains the same). Is there a way to make ggplot ignoring the NA/empty this way so that the lines will stop at this points?

expected result: MTA Chart

Thanks for your help!

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source