Reputation: 2763
I am plotting a time series that looks like this:
library(ggplot2)
df1 <- data.frame(date=as.Date(seq(ISOdate(2019,1,1), by="1 day", length.out=365)),
value=runif(365))
df2 <- data.frame(date=as.Date(seq(ISOdate(2019,1,1), by="1 day", length.out=365)),
value=runif(365)+3)
ggplot() +
geom_line(df1, mapping=aes(x=date, y=value)) +
geom_line(df2, mapping=aes(x=date, y=value)) +
geom_vline(aes(xintercept=as.Date("2019-06-15"), colour="Milestone 1"), linetype="dashed") +
geom_vline(aes(xintercept=as.Date("2019-07-20"), colour="Milestone 2"), linetype="dashed") +
geom_vline(aes(xintercept=as.Date("2019-09-15"), colour="Milestone 3"), linetype="dashed") +
scale_color_manual(name="Milestones",
breaks=c("Milestone 1","Milestone 2","Milestone 3"),
values = c("Milestone 1" = "red",
"Milestone 2" = "blue",
"Milestone 3" = "green"))
However, I would like to add colors and a separate legend for the geom_lines
mapped in df1
and df2
.
How to achieve that?
Upvotes: 0
Views: 1368
Reputation: 26695
Is this what you're trying to do?
library(tidyverse)
df1 <- data.frame(date=as.Date(seq(ISOdate(2019,1,1), by="1 day", length.out=365)),
value=runif(365))
df2 <- data.frame(date=as.Date(seq(ISOdate(2019,1,1), by="1 day", length.out=365)),
value=runif(365)+3)
df1$Lines <- factor("Line 1")
df2$Lines <- factor("Line 2")
df3 <- rbind(df1, df2)
ggplot(df3) +
geom_line(df3, mapping = aes(x = date, y = value, alpha = Lines)) +
geom_vline(aes(xintercept = as.Date("2019-06-15"), colour = "Milestone 1"), linetype = "dashed") +
geom_vline(aes(xintercept = as.Date("2019-07-20"), colour = "Milestone 2"), linetype = "dashed") +
geom_vline(aes(xintercept = as.Date("2019-09-15"), colour = "Milestone 3"), linetype = "dashed") +
scale_color_manual(name="Milestones",
breaks=c("Milestone 1","Milestone 2","Milestone 3"),
values = c("Milestone 1" = "red",
"Milestone 2" = "blue",
"Milestone 3" = "green"))
Upvotes: 2