Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 494
LoveMeow Avatar asked Oct 11 '11 04:10

LoveMeow


People also ask

How do I color a point by a variable in R?

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.

How do I specify colors in 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)

How do I make a grouped scatter plot in R?

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.


2 Answers

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.

like image 85
Maiasaura Avatar answered Sep 24 '22 03:09

Maiasaura


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.

like image 43
John Avatar answered Sep 23 '22 03:09

John