【问题标题】:Adding a legend to a ggplot with a scatterplot and a line graph使用散点图和折线图向 ggplot 添加图例
【发布时间】:2019-08-05 13:25:21
【问题描述】:

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

我的数据是 JetFuelHedging.csv 来自 Introduction to Quantitative Finance in R,可以找到 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))

【问题讨论】:

    标签: r ggplot2 plot quantitative-finance


    【解决方案1】:

    要获得 Legends,您应该在 aes() 中包含 colour

    试试这个-

    > 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2015-06-29
      • 2016-08-10
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多