Colouring plot by factor in R

LoveMeow picture LoveMeow · Oct 11, 2011 · Viewed 262.5k times · Source

I am making a scatter plot of two variables and would like to colour the points by a factor variable. Here is some reproducible code:

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

This is all well and good but how do I know what factor has been coloured what colour??

Answer

Maiasaura picture Maiasaura · Oct 11, 2011
data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)

should do it for you. But I prefer ggplot2 and would suggest that for better graphics in R.