Charles Trautner
Charles Trautner

Reputation: 1

How can I color points in a range in a dataset on a scatterplot in R

I need to make a color-coded scatter plot from imported data where values between 0 and 4 are colored red. I tried subsetting but I don't think I'm using it correctly. Heres the code I'm trying to use

DAT1 = log(DAT, 10)
data.frame(DAT1)
FSC = DAT1$FSC.HLin
RED = DAT1$RED.V.HLin
plot(FSC, RED)
red = subset(DAT1, FSC.HLin<4 & FSC.HLin>0)
points(red)
col = 'red'

Upvotes: 0

Views: 770

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76412

Here is a way of plotting the selected points in a different color with ifelse. Set graphics parameter col to the values "red" and "black" depending on the x axis values.

FSC <- -5:10
RED <- seq_along(FSC)
plot(FSC, RED, col = ifelse(FSC > 0 & FSC < 4, "red", "black"))

enter image description here

Another, equivalent way is to create a vector of colors beforehand. In the code that follows I also change the point character to solid circle, though this is not in the question. And use the data set DAT1 directly without creating new vectors FSC and RED.

DAT1 <- data.frame(FSC.HLin = FSC, RED.V.HLin = RED)
col <- with(DAT1, ifelse(FSC.HLin > 0 & FSC.HLin < 4, "red", "black"))
pch <- with(DAT1, ifelse(FSC.HLin > 0 & FSC.HLin < 4, 16, 1))
plot(RED.V.HLin ~ FSC.HLin, data = DAT1, col = col, pch = pch)

enter image description here

Upvotes: 1

Related Questions