Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R color scatter plot points based on values

Tags:

r

I am able to plot a scatter plot and color the points based on one criteria, i.e. I can color all points >=3 as red and the remainder as black. I would love to be able to color points in this fashion:

  1. =3 color red

  2. <=1 color blue
  3. The rest as black

The code I have below completes step 1 and 3 but I am not sure how to incorporate the second argument of step 2

data<- read.table('sample_data.txtt', header=TRUE, row.name=1) pos<- data$col_name1 cn<- data$col_name2 plot(pos,cn, ylim=c(0,5), col="blue") plot(pos,cn, col=ifelse(cn>=3,"red","black"), ylim=c(0,10)) 

Any help would be great!!! Thanks in advance

enter image description here

like image 275
Jcrow06 Avatar asked Jul 09 '13 14:07

Jcrow06


People also ask

How do you color a point in a scatterplot in R?

The different color systems available in R have been described in detail here. To change scatter plot color according to the group, you have to specify the name of the data column containing the groups using the argument groupName . Use the argument groupColors , to specify colors by hexadecimal code or by name .

How do I change the color of my plot points in R?

Output: Now to change the colors of a scatterplot using plot(), simply select the column on basis of which different colors should be assigned to various points. Pass the column that will help differentiate between points to “col” attribute.

How do I plot colors in R?

In R, the color black is denoted by col = 1 in most plotting functions, red is denoted by col = 2 , and green is denoted by col = 3 . So if you're plotting multiple groups of things, it's natural to plot them using colors 1, 2, and 3.


2 Answers

Best thing to do here is to add a column to the data object to represent the point colour. Then update sections of it by filtering.

data<- read.table('sample_data.txtt', header=TRUE, row.name=1) # Create new column filled with default colour data$Colour="black" # Set new column values to appropriate colours data$Colour[data$col_name2>=3]="red" data$Colour[data$col_name2<=1]="blue" # Plot all points at once, using newly generated colours plot(data$col_name1,data$col_name2, ylim=c(0,5), col=data$Colour, ylim=c(0,10)) 

It should be clear how to adapt this for plots with more colours & conditions.

like image 54
CnrL Avatar answered Sep 17 '22 13:09

CnrL


Also it'd work to just specify ifelse() twice:

plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10)) 
like image 20
tim riffe Avatar answered Sep 20 '22 13:09

tim riffe