I have a ggplot2 line chart made from three data frames for which I have controlled the color scheme. I've instead used linetype to distinguish between lines. This leads to a situation in which a legend is not automatically generated. How can I create a legend for this plot?
tpAct <- data.frame(
Date=seq.Date(as.Date('2017-09-01'), as.Date('2018-01-01'),by='month'),
Reg1=rnorm(5, 10, 5),
Reg2=rnorm(5, 15, 5),
Reg3=rnorm(5, 20, 5),
Reg4=rnorm(5, 25, 5),
Reg5=rnorm(5, 30, 5),
Total=rnorm(5, 60, 5)
)
tpOL <- data.frame(
Date=seq.Date(as.Date('2017-09-01'), as.Date('2018-01-01'),by='month'),
Reg1=rnorm(5, 10, 5),
Reg2=rnorm(5, 25, 5),
Reg3=rnorm(5, 20, 5),
Reg4=rnorm(5, 25, 5),
Reg5=rnorm(5, 30, 5),
Total=rnorm(5, 60, 5)
)
tpModL2 <- data.frame(
Date=seq.Date(as.Date('2017-09-01'), as.Date('2018-01-01'),by='month'),
Reg1=rnorm(5, 10, 5),
Reg2=rnorm(5, 25, 5),
Reg3=rnorm(5, 20, 5),
Reg4=rnorm(5, 25, 5),
Reg5=rnorm(5, 30, 5),
Total=rnorm(5, 60, 5)
)
ggplot() +
geom_line(data=tpAct, aes(x=Date, y=Reg1), color='red', size=1.25) +
geom_line(data=tpAct, aes(x=Date, y=Reg2), color='blue', size=1.25) +
geom_line(data=tpAct, aes(x=Date, y=Reg3), color='green', size=1.25) +
geom_line(data=tpAct, aes(x=Date, y=Reg4), color='pink', size=1.25) +
geom_line(data=tpAct, aes(x=Date, y=Reg5), color='yellow', size=1.25) +
geom_line(data=tpAct, aes(x=Date, y=Total), color='black', size=1.25) +
geom_line(data=tpOL, aes(x=Date, y=Reg1), linetype=5, color='red', size=1.25) +
geom_line(data=tpOL, aes(x=Date, y=Reg2), linetype=5, color='blue', size=1.25) +
geom_line(data=tpOL, aes(x=Date, y=Reg3), linetype=5, color='green', size=1.25) +
geom_line(data=tpOL, aes(x=Date, y=Reg4), linetype=5, color='pink', size=1.25) +
geom_line(data=tpOL, aes(x=Date, y=Reg5), linetype=5, color='yellow', size=1.25) +
geom_line(data=tpOL, aes(x=Date, y=Total), linetype=5, color='black', size=1.25) +
geom_line(data=tpModL2, aes(x=Date, y=Reg1), linetype=4, color='red', size=1.25) +
geom_line(data=tpModL2, aes(x=Date, y=Reg2), linetype=4, color='blue', size=1.25) +
geom_line(data=tpModL2, aes(x=Date, y=Reg3), linetype=4, color='green', size=1.25) +
geom_line(data=tpModL2, aes(x=Date, y=Reg4), linetype=4, color='pink', size=1.25) +
geom_line(data=tpModL2, aes(x=Date, y=Reg5), linetype=4, color='yellow', size=1.25) +
geom_line(data=tpModL2, aes(x=Date, y=Total), linetype=4, color='black', size=1.25) +
labs(x='', y='Total Balances ($B)')



linetypeand you'll have your legend.geom_line. To do that, (1) convert the individual data frames to long format, (2) stack the individual data frames into a single data frame and add an indicator column to mark the name of the source data frame. Then you can map the source data frame to linetype andRegto color, which will give you a legend and drastically reduce the amount of code needed. If you provide samples of each of your three data frames, we can provide code to show you how to do this.