R: Coloring plots


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


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" />


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


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)


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()


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


  • How to make labels in the legend align right in R?
  • Mysql query of inverted index data
  • Trying to fill large gap in pie chart using ggplot2
  • Create data.frame conditional on another df without for loop
  • How can I plot two cumulative distributions curve as line type in same plot
  • Should I use regex or just DOM/string manipulation? [closed]
  • Extending / converting a sparse matrix into a larger sparse matrix
  • Are there named groups in Groovy regex pattern matches?
  • Create columns in R within a for loop
  • Comparing matrix inversions in R - what is wrong with the Cholesky method?
  • Some changes in a bubbleplot (ggplot)
  • How could I calculate an expression across the slices of a 3D-array?
  • Is there any way to generate uncorrelated random variables using Python?
  • Tooltips for high points on low-height charts not displaying
  • Subset of predictors using coefplot()
  • looping through pairs of input files [duplicate]
  • How to combine two plots in R?
  • passing string to ggplot function
  • strtotime returns incorrect timestamp for '-1 month'
  • string Multiplication in C++
  • href inside href [duplicate]
  • Combine two small queries (that group by different values) into one query
  • Direct insert data in mysql data in android
  • R h2o.glm - issue with max_active_predictors
  • Layout design help Android
  • How to plot large time series (thousands of administration times/doses of a medication)?
  • using System.Speech.Synthesis with Windows10 universal app (XAML-C#)
  • GAE: Way to get reference to an HttpSession from its ID?
  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • Generate random number from custom distribution
  • What is the purpose of TaskExecutor in spring?
  • gspread or such: help me get cell coordinates (not value)
  • align graphs with different xlab
  • Comma separated Values
  • Error creating VM instance in Google Compute Engine
  • Hits per day in Google Big Query
  • how does django model after text[] in postgresql [duplicate]
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • java string with new operator and a literal