Reputation: 27
I have data which is packed into two columnsm (x,y). I want to produce a scatterplot with three different colours which reflect the value of y. So for all values of x,y below y1 (say 1) I want to have colour 1, for values of x,y between y1 and y2 I would like to have colour two and finally for values of y higher than y2 I would like to have a third colour. How could I achieve this in R?
Thanks
Upvotes: 3
Views: 2511
Reputation: 121608
Another option is to use a nested ifelse
to define the color.
Using @Ricardo data:
dat <- data.frame(x = rnorm(100),y = rnorm(100))
with(dat,
plot(y~x, col=ifelse(y<y1,'red',
ifelse(y>y2,'blue','green')), pch=19))
Upvotes: 5
Reputation: 4349
You can create the color levels using cut
, then using the vector of colors in your plot
.
set.seed(1104)
x = rnorm(100)
y = rnorm(100)
colors = c("blue", "red", "green")
breaks = c(y1=0, y2=1)
# first plot (given breaks values)
y.col2 = as.character(cut(y, breaks=c(-Inf, breaks, Inf), labels=colors))
plot(x, y, col=y.col2, pch=19)
# second plot (given number of breaks)
y.col = as.character(cut(y, breaks=3, labels=colors))
plot(x, y, col=y.col, pch=19)
Upvotes: 6