Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-add legend in [R]?

Tags:

r

legend

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

enter image description here

like image 510
TMOTTM Avatar asked Sep 30 '22 02:09

TMOTTM


1 Answers

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)

enter image description here

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

enter image description here

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

enter image description here

like image 170
jbaums Avatar answered Oct 26 '22 02:10

jbaums