简体   繁体   English

使用散点图和折线图将图例添加到ggplot

[英]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. 我在一张图上有混合的散点图和线图ggplot。 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? 在ggplot中这可能吗?

My data is JetFuelHedging.csv from Introduction to Quantitative Finance in R, which can be found here 我的数据是R中的定量金融简介中的JetFuelHedging.csv,可在此处找到

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() . 要获得图例,您应该在aes()包含colour

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 ggplot2自定义图例形状

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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