rggplot2graph

How to transition a line from solid to dotted


I got the following data on Ecuador's GDP growth and forecast by the IMF.

I want to make a graph, that from 2015 to 2021 is a line (geom_line), but from 2022 to 2026 is a dotted line, I want this to show that from 2022 is the forecast.

This is my code, but I don't know how to state the condition.

forecast %>%
 filter(Year >= 2015L & Year <= 2026L) %>%
 ggplot() +
 aes(x = Year, y = `Real GDP Growth`) +
 geom_line(size = 0.75, colour = "#B22222") +
 labs(x = "Year", y = "GDP Growth", title = "Ecuador's Real GDP growth Forecast", subtitle = "Forecast done by the World Economic Outlook") +
 theme_light() +
 theme(plot.title = element_text(size = 18L, face = "bold", hjust = 0.5), plot.subtitle = element_text(size = 13L, 
 hjust = 0.5), axis.title.y = element_text(size = 13L, face = "bold"), axis.title.x = element_text(size = 13L, 
 face = "bold"))+scale_x_continuous(n.breaks=11)+geom_hline(yintercept = 0, lty=5, size=0.75)

enter image description here


Here is the data:

structure(list(Year = c(1980, 1981, 1982, 1983, 1984, 1985, 1986, 
1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 
2020, 2021, 2022, 2023, 2024, 2025, 2026), `Real GDP Growth` = c(4.9, 
3.9, 1.2, -2.8, 4.2, 4.4, 3.1, -6, 10.5, 0.3, 3, 5.1, 3.6, 2, 
4.3, 2.3, 1.7, 4.3, 3.3, -4.7, 1.1, 4, 4.1, 2.7, 8.2, 5.3, 4.4, 
2.2, 6.4, 0.6, 3.5, 7.9, 5.6, 4.9, 3.8, 0.1, -1.2, 2.4, 1.3, 
0, -7.8, 2.8, 3.5, 2.5, 2.6, 2.8, 2.8)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -47L))

The final graph, should look like this: enter image description here


Solution

  • Give this a go - I subset your data into two groups for the two line types, and did a bit of reorganization and simplification of the rest:

    ggplot() +
      aes(x = Year, y = `Real GDP Growth`) +
      geom_line(data = filter(forecast, Year <= 2021), size = 0.75, colour = "#B22222") +
      geom_line(data = filter(forecast, Year >= 2021), size = 0.75, colour = "#B22222", linetype = "dotted") +
      labs(
        x = "Year", y = "GDP Growth", 
        title = "Ecuador's Real GDP growth Forecast", 
        subtitle = "Forecast done by the World Economic Outlook") +
      scale_x_continuous(n.breaks = 11) + 
      geom_hline(yintercept = 0, lty = 5, size = 0.75) +
      theme_light() +
      theme(
        plot.title = element_text(size = 18L, face = "bold", hjust = 0.5),
        plot.subtitle = element_text(size = 13L, hjust = 0.5),
        axis.title = element_text(size = 13L, face = "bold")
      ) 
    

    enter image description here