ggplot: changing line type after certain years

In the example below, can I change the line type after certain years, say, starting from year 2000? In other words, colors would remain the same; just line type would change from solid to dotted.

gapminder %>% 
  filter(country %in% c("United States", "United Kingdom", "Australia",
                        "India", "Pakistan", "Bangladesh")) %>% 
  ggplot(aes(x = year, y = lifeExp, color = country)) +

Created on 2020-09-26 by the reprex package (v0.3.0)

Here is one rather fiddly method.

library(dplyr, warn.conflicts = FALSE)

DF <- data.frame(Year = rep(1995:2004, each = 2),
                 Country = rep(c("Mex", "Canada"), 10),
                 Value = rnorm(20, 5, 10))
Early <- DF %>% filter(Year <= 2000)
Late <- DF %>% filter(Year >= 2000)
ggplot(mapping = aes(Year, Value, color = Country, group = Country)) + 
  geom_line(linetype = 1, data = Early) + geom_line(linetype = 2, data = Late) 

Created on 2020-09-26 by the reprex package (v0.3.0)

1 Like

Thanks a lot! Just what I wanted.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.