简体   繁体   中英

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM