2

Is there a way to have the following line plotted in a red and dashed type after June 01 ?

library(tidyverse)
DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2001-09-30"), by = "days"),
                  V1 = runif(273, 1, 10))
ggplot(DF, aes(x = Date, y = V1))+
  geom_line()
tjebo
  • 21,977
  • 7
  • 58
  • 94
Hydro
  • 1,057
  • 12
  • 25
  • Does this answer your question? [ggplot line plot different colors for sections](https://stackoverflow.com/questions/47498588/ggplot-line-plot-different-colors-for-sections) – tjebo Jun 19 '20 at 15:03

2 Answers2

3

You can create a new variable based on whether dates are after June 1 or not.

DF$x <- DF$Date>as.Date('2001-06-01')

ggplot(DF, aes(x = Date, y = V1, col=x))+
  geom_line(aes(lty=x), show.legend=FALSE) +
  scale_color_manual(values=c("black","red"))

enter image description here

Required libraries:

library(ggplot2)
Edward
  • 10,360
  • 2
  • 11
  • 26
1

You could subset DF

ggplot(DF[DF$Date < as.Date("2001-06-01"), ], aes(x = Date, y = V1)) +
  geom_line() +
  geom_line(data = DF[DF$Date >= as.Date("2001-06-01"), ], col = "red", linetype = "dashed")

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68