Adrian Adrian - 1 year ago 87
R Question

R: adding a plot legend in R

plot(iris$Sepal.Length, iris$Sepal.Width, col = iris$Species)

enter image description here

I know that I can use the
function to manually set my legend. However, I have no idea which color was assigned to the different species in my data? Is there an automatic way to get
to add a legend?

Answer Source

As @rawr says, palette() determines the colour sequence used. If you use integers to specify colours, it will also look at palette(). Thus

with(iris,plot(Sepal.Length, Sepal.Width, col = Species))
legend("topright",legend=levels(iris$Species),col=1:3, pch=1)

works nicely.

enter image description here

Base R doesn't have an auto-legend facility: the ggplot2 package does.


gives you a plot with an automatic legend (use theme_set(theme_bw()) if you don't like the grey background).

enter image description here

The built-in lattice package can also do automatic legends:


enter image description here