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

时间:2019-08-05 13:25:21

标签: r ggplot2 plot quantitative-finance

我在一张图上有混合的散点图和线图ggplot。散点图和折线图基于不同的数据。点为蓝色,线为红色。我想添加一个图例,该图例显示对应于数据的蓝点和对应于红线中数据的红线。 ggplot中有可能吗?

我的数据是《 R中的定量金融概论》中的JetFuelHedging.csv,可在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))

1 个答案:

答案 0 :(得分:3)

要获取图例,您应该在colour中加入aes()

试试这个-

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

要编辑图例形状,您可以参考此-

ggplot2 custom legend shapes