Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scatterplot colour based on y-value

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

like image 918
user2533698 Avatar asked Aug 24 '26 09:08

user2533698


2 Answers

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)

theplot

like image 118
Ricardo Oliveros-Ramos Avatar answered Aug 27 '26 00:08

Ricardo Oliveros-Ramos


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

enter image description here

like image 26
agstudy Avatar answered Aug 26 '26 23:08

agstudy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!