使用散点图和折线图向 ggplot 添加图例
Adding a legend to a ggplot with a scatterplot and a line graph
我在一张图上混合了散点图和折线图 ggplot。散点图和折线图基于不同的数据。点是蓝色的,线是红色的。我想添加一个图例,显示与数据对应的蓝点和与红线中的数据对应的红线。这在 ggplot 中可行吗?
我的数据是JetFuelHedging.csv来自Introduction to Quantitative Finance in R 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))
要获得传奇,您应该在 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'))
编辑Legend Shapes可以参考这个-
ggplot2 custom legend shapes
我在一张图上混合了散点图和折线图 ggplot。散点图和折线图基于不同的数据。点是蓝色的,线是红色的。我想添加一个图例,显示与数据对应的蓝点和与红线中的数据对应的红线。这在 ggplot 中可行吗?
我的数据是JetFuelHedging.csv来自Introduction to Quantitative Finance in R 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))
要获得传奇,您应该在 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'))
编辑Legend Shapes可以参考这个-
ggplot2 custom legend shapes