Reputation: 2623
I have a mixed scatter plot and line graph ggplot on one graph. The scatter point and line graphs are based on different data. The points are in blue and the line is in red. I want to add a legend that shows a blue point corresponding to the data and a red line corresponding the data in the red line. Is this possible in ggplot?
My data is JetFuelHedging.csv from Introduction to Quantitative Finance in R, which can be found here
price <- read.csv("JetFuelHedging.csv")
price$Date <- as.Date(as.yearmon(price$Date))
ggplot(price, aes(x=Date, group = 1))+
geom_point(aes(y = JetFuel), colour = "dodgerblue2")+
geom_line(aes(y=HeatingOil), color = "Red")+
labs(x = "Month", y = "USD")+
scale_x_date(date_breaks = "6 months", date_labels = "%b %Y")+
theme(axis.text.x=element_text(angle=60, hjust=1))
Upvotes: 2
Views: 5419
Reputation: 2764
To get Legends, you should include colour
in aes()
.
Try this-
> price$Date <- as.Date(as.yearmon(price$Date))
> ggplot(price, aes(x=Date, group = 1))+
geom_point(aes(y = JetFuel, colour = "dodgerblue2"),show.legend = T)+
geom_line(aes(y=HeatingOil, colour = "Red"),show.legend = T)+
labs(x = "Month", y = "USD")+
scale_x_date(date_breaks = "6 months", date_labels = "%b %Y")+
theme(axis.text.x=element_text(angle=60, hjust=1)) +
scale_colour_manual(name = 'Legend',
guide = 'legend',
values = c('dodgerblue2' = 'blue',
'Red' = 'red'),
labels = c('Points',
'Line'))
To edit Legend Shapes you can refer to this-
Upvotes: 3