How do I automatically add a legend to [R]?

plot(airquality$Wind, airquality$Ozone, col=airquality$Month)

      

How do I add a legend to a graph with correctly assigned colors, other than manually figuring out which color codes for which Month

?


EDIT And after ordering a very nice plot comes out:

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

      

enter image description here

+3


source to share


1 answer


The numbers in airquality$Month

represent specific colors (as well as specific months). You can use R for these numbers when building the legend:

legend('topright', month.abb[unique(airquality$Month)], 
       col=unique(airquality$Month), pch=21)

      

enter image description here

Alternatively lattice

provides an argument auto.key

, like its function xyplot

:

library(lattice)
xyplot(airquality$Ozone ~ airquality$Wind, groups=airquality$Month,
       auto.key=list(title="Month", corner=c(0.95, 1)))

      



enter image description here

EDIT: And the approach ggplot

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

      

enter image description here

+3


source







All Articles