plot(airquality$Wind, airquality$Ozone, col=airquality$Month)
How can I add a legend to the plot with correctly assigned colors other than by manually figuring out which color codes for which Month?
EDIT And after ordering one gets a really nice plot:
with(
airquality,
xyplot(airquality[order(Wind), ]$Ozone ~ airquality[order(Wind), ]$Wind,
groups=Month, type="b",
auto.key=list(title="Month", corner=c(0.95, 1.0)))
)

The numbers contained in airquality$Month define specific colors (as well as specific months). You can have R use these numbers when constructing the legend:
legend('topright', month.abb[unique(airquality$Month)],
col=unique(airquality$Month), pch=21)

Alternatively, lattice provides the auto.key argument to, e.g., its xyplot function:
library(lattice)
xyplot(airquality$Ozone ~ airquality$Wind, groups=airquality$Month,
auto.key=list(title="Month", corner=c(0.95, 1)))

EDIT:
And the ggplot approach, as provided by @MrFlick in the comments.
library(ggplot2)
ggplot(airquality,
aes(Wind, Ozone, col=factor(Month, levels=1:12, labels=month.name))) +
geom_point() + scale_color_discrete(name="Month")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With