[R] color ranges on a 2D plot

Marc Schwartz marc_schwartz at comcast.net
Wed Jan 16 22:20:01 CET 2008


dxc13 wrote:
> useR's
>
> I am trying to color the points on a scatter plot (code below) with two
> colors.  Red for values 0.5 -1.0 and blue for 0.0 - .49.  Does anyone know a
> easy way to do this?
>
> x<- runif(100, 0, 1)
> y<- runif(100, 0, 1)
> plot(y ~ x, pch=16)
>
> Thanks,
> dxc13

You did not specify if this is for just the 'x' values, the 'y' values, 
or both. If the latter, more than two colors might make sense.

For just the 'x' values and two colors, the easiest might be something like:

   plot(x, y, col = ifelse(x >= 0.5, "red", "blue"))

Change 'x' to 'y' for the same on 'y'.


Alternatively, you could do something like the following for coloring 
based upon both 'x' and 'y':

cols <- character(length(x))

xgt <- x >= 0.5
ygt <- y >= 0.5

cols[which(xgt & ygt)] <- "black"
cols[which(!xgt & ygt)] <- "red"
cols[which(xgt & !ygt)] <- "blue"
cols[which(!xgt & !ygt)] <- "green"

plot(x, y, col = cols, pch = 16)


HTH,

Marc Schwartz




More information about the R-help mailing list