Clarinetist
Clarinetist

Reputation: 1187

Changing Line Type for specified interval in time series (solid to dotted)

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?

Upvotes: 3

Views: 1229

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23101

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

Upvotes: 1

Related Questions