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??
One of the ways to add color to scatter plot by a variable is to use color argument inside global aes() function with the variable we want to color with. In this scatter plot we color the points by the origin airport using color=origin. The color argument has added colors to scatterplot with default colors by ggplot2.
A color can be specified either by name (e.g.: “red”) or by hexadecimal code (e.g. : “#FF1234”). The different color systems available in R are described at this link : colors in R. In this R tutorial, you will learn how to : change colors by groups (automatically and manually)
If you have a grouping variable you can create a scatter plot by group passing the variable (as factor) to the col argument of the plot function, so each group will be displayed with a different color.
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.
The command palette
tells you the colours and their order when col = somefactor
. It can also be used to set the colours as well.
palette() [1] "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
In order to see that in your graph you could use a legend.
legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.
You could also be specific about the colours. Try ?rainbow
for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With