bdeonovic
bdeonovic

Reputation: 4220

R: Coloring plots

I have some data that I want to plot (e.g. plot(x,y)) but I have some criteria that I want to color by depending on the values in vector z which looks like c(1, 0, 1, 1, 1, 1, 0, NA ,0 ,0, .....) etc.

Is there some way I can choose what color the 1's are going to be and what color the 0's are going to be?

Thanks

Upvotes: 0

Views: 278

Answers (5)

user2005253
user2005253

Reputation:

I know this has already been answered but here is some very intuitive code with a plot for reference.

#Let's create some fictional data 
x = rbinom(100,1,.5)
x[round(runif(10)*100)] = NA

#Assign colors to 1's and 0's
colors = rep(NA,length(x))
colors[x==1] = "blue"
colors[x==0] = "red" 

#Plot the vector x
plot(x,bg=colors,pch=21)

enter image description here

Upvotes: 4

srmulcahy
srmulcahy

Reputation: 469

Using the ggplot2 package

require(ggplot2)

df <- data.frame(x = c(1, 2, 3, 4, 5), y = c(2, 3, 4, 6, 7), z = c(1, 0 , 1, 0 , NA))
df$z[is.na(df$z)] = 2
ggplot(df, aes(x, y, color = as.factor(z))) + geom_point()

Upvotes: 2

Didzis Elferts
Didzis Elferts

Reputation: 98589

You can supply vector of colors to argument col= and then use z to select colors. Used paste() to convert NA to character and then as.factor() to interpret those characters as 1, 2 and 3.

x<-c(1,2,3,4,5)
y<-c(1,2,3,4,5)
z<-c(1,0,NA,1,1)
plot(x,y,col=c("red","green",'black')[as.factor(paste(z))],pch=19,cex=3)

str(as.factor(paste(z)))
Factor w/ 3 levels "0","1","NA": 2 1 3 2 2

Upvotes: 1

nograpes
nograpes

Reputation: 18323

Maybe I am missing something, but I think you want:

plot(x,y,col=ifelse(z==0,'zerocolour','onecolour'))

where you replace the two colours with red and blue or whatever.

I don't think the NA will be plotted, so you don't have to worry about those.

For more colours, you could create a little mapping data.frame with the unique values of z, and then merge z with the data.frame. Here is an example with two colours:

map<-data.frame(z=c(0,1),col=c('red','blue'))
plot(x,y,col=merge(z,map)$col)

Upvotes: 2

David Robinson
David Robinson

Reputation: 78630

You want to get a vector of colors as long as the x and y vectors, for example as follows:

z[is.na(z)] = 2
zcol = c("red", "blue", "black")[z + 1]

Then you can simply do:

plot(x, y, col=zcol)

Upvotes: 3

Related Questions