Search code examples
rcolorsplotr-factor

Colouring plot by factor in R


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


Solution

  • 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.