3

Consider the following example:

library(ggplot2)
set.seed(30)

data <- data.frame(group = factor(1:11), 
                   year = c(rep(2014, times = 11), 
                            rep(2015, times = 11), 
                            rep(2016, times = 11), 
                            rep(2017, times = 11)), 
                   value = runif(44))

data$year <- as.Date(as.character(data$year), 
                     format = "%Y")

ggplot(data, aes(x = year, y = value, color = group)) +
  geom_point() + 
  geom_line() + 
  theme_bw()

enter image description here

I would like all lines to the right of when year == 2015 to be dotted, and all lines to the left of when year == 2015 to remain solid. How can this be done?

Clarinetist
  • 1,097
  • 18
  • 46

1 Answers1

1

You can try this:

library(ggplot2)
set.seed(30)

data <- data.frame(group = factor(1:11), 
                   year = c(rep(2014, times = 11), 
                            rep(2015, times = 11), 
                            rep(2016, times = 11), 
                            rep(2017, times = 11)), 
                   value = runif(44))

data$int_year <- data$year
data$year <- as.Date(as.character(data$year), 
                     format = "%Y")

ggplot(subset(data, int_year <= 2015), aes(x = year, y = value, color = group)) +
  geom_point() + 
  geom_line() + 
  geom_line(data=subset(data, int_year >= 2015), aes(x = year, y = value, color = group), lty=2) + 
  theme_bw()

enter image description here

[EDITED]

data1 <- subset(data, int_year <= 2015)
data2 <- subset(data, int_year >= 2015)
ggplot(data1, aes(x = year, y = value, color = group)) +
  geom_point() + 
  geom_line() + 
  geom_point(data=data2, aes(x = year, y = value, color = group)) + 
  geom_line(data=data2, aes(x = year, y = value, color = group), lty=2) + 
  theme_bw()

enter image description here

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
  • 1
    Thank you. As a side question, if I still want to show the points (the circular dots) in the dotted lines, how would I go about doing this? – Clarinetist Feb 06 '17 at 17:10
  • 2
    A slightly simpler approach is to just plot everything as dotted, and then rep-plot the solid parts over them: `ggplot(data, aes(x = year, y = value, color = group)) + geom_point() + geom_line(linetype = 2) + geom_line(data = subset(data, year <= '2015-02-06')) + theme_bw()` – alistaire Feb 06 '17 at 17:12
  • @Clarinetist: edited and updated the code to add the points too. – Sandipan Dey Feb 06 '17 at 17:15