Mr.Rlover
Mr.Rlover

Reputation: 2623

Adding a legend to a ggplot with a scatterplot and a line graph

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

Answers (1)

Rushabh Patel
Rushabh Patel

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-

ggplot2 custom legend shapes

Upvotes: 3

Related Questions