R 使用散点图和折线图向ggplot添加图例

R 使用散点图和折线图向ggplot添加图例,r,ggplot2,plot,quantitative-finance,R,Ggplot2,Plot,Quantitative Finance,我有一个混合散点图和一个图上的线图。散布点和线图基于不同的数据。点是蓝色的,线是红色的。我想添加一个图例,显示与数据相对应的蓝点和与红线中的数据相对应的红线。这在ggplot中是可能的吗 我的数据是R定量金融导论中的jetfuelhedgeg.csv,可以找到 price要获取图例,您应该在aes()中包含color 试试这个- > price$Date <- as.Date(as.yearmon(price$Date)) > ggplot(price, aes(x=Date

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

我的数据是R定量金融导论中的jetfuelhedgeg.csv,可以找到


price要获取图例,您应该在
aes()中包含
color

试试这个-

> 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'))
>price$Date ggplot(价格,aes(x=Date,group=1))+
几何点(aes(y=JetFuel,color=“dodgerblue2”),show.legend=T)+
geom_线(aes(y=加热油,颜色=“红色”),show.legend=T)+
实验室(x=“月”,y=“美元”)+
缩放日期(日期间隔=“6个月”,日期标签=“%b%Y”)+
主题(axis.text.x=元素\文本(角度=60,hjust=1))+
比例颜色手册(名称=‘图例’,
指南='图例',
值=c('dodgerblue2'='blue',
“红色”=“红色”),
标签=c('点',
"行"))
要编辑图例形状,可以参考以下内容-

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