I have some data that I want to plot (e.g.
plot(x,y)) but I have some <em>criteria that I want to color by</em> 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?
You want to get a vector of colors as long as the
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)Answer2:
I know this has already been answered but here is some <strong>very</strong> 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)
<img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/7QOLK.png" data-original="https://i.stack.imgur.com/7QOLK.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />Answer3:
Maybe I am missing something, but I think you want:
where you replace the two colours with
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:
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()Answer5:
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