Adrian Adrian - 2 months ago 17
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
legend()
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
plot()
to add a legend?

Answer

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.

library(ggplot2)
ggplot(iris,aes(Sepal.Length,Sepal.Width,colour=Species))+geom_point()

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:

library(lattice)
xyplot(Sepal.Width~Sepal.Length,group=Species,data=iris,auto.key=TRUE)

enter image description here