当有两个 y 变量时如何添加图例?

How do I add legends when there are two y variables?

这是我使用的代码:

ggplot(Delays2006, aes(Month)) + geom_point(aes(y = delay), color = "blue", size = 2) 
+ geom_point(aes(y=delay2)) + scale_x_discrete(limits=(month.name))
+ labs(x= "Months", y = "Delays in minutes") + ggtitle(" Flight Data 2006")

这是输出:

请问如何在这个图中给delay和delay2添加图例。谢谢。

如果你想有一个传奇,你必须在美学上进行映射,即 geom_point(aes(y = delay, color = "delay")) + geom_point(aes(y=delay2, color = "delay2"))。然后可以通过 scale_color_manual.

设置颜色和标签

使用 mtcars 作为示例数据:

library(ggplot2)

ggplot(mtcars, aes(mpg)) +
  geom_point(aes(y = hp, color = "hp")) +
  geom_point(aes(y = cyl, color = "cyl")) +
  scale_color_manual(values = c(hp = "blue", cyl = "green"), labels = c(hp = "Horse Power", cyl = "Cylinders"))