Question: coloring a plot
0
friasoler20 wrote:

Hello everyone! I would like to have a plot with some points in different colors; but I get an empty plot. Could someone help me?

``````a=data.frame(b= c(1:26), c=rnorm(26), d=paste(letters[1:26]))
e=data.frame(a\$d[3:15])
colnames(e)=c("d1")
``````

# variant 1

``````plot(a\$b, a\$c, col= (if (a\$b<5) {'red'} else (for (i in 1:26) {if (a\$d[i] == e\$d1) {'blue'} else {'black'}})))
``````

Warning message: In if (a\$b < 5) { : the condition has length > 1 and only the first element will be used

# variant 2

``````plot(a\$b, a\$c, col= for (i in 1:26) {if (a\$d[i]%in%e\$d1) {'blue'} else {'black'}})
``````

Warning message: In if (a\$b < 5) { : the condition has length > 1 and only the first element will be used

d are the labels of each element coordinates (b;c), number of elements =26

e: data frame with a subset of character elements from a\$d

I would like the elements a\$b < 5 in red, a\$d == e\$d1 to b colored in ‘blue’ and the rest in ‘black’ Thanks in advance Roberto

modified 2.5 years ago • written 2.5 years ago by friasoler20
0
VHahaut1.1k wrote:

``````plot(a\$b, a\$c, col= ifelse((a\$d%in%e\$a.d.3.15.), "blue", "black"))
``````

the problem lies in your conditionnal statement.

NB: `e=data.frame(a\$d[3:15])` should be `e=data.frame(d1=a\$d[3:15])` if you want to use `e\$d1` afterwards.

Update: here is a conditionnal statement for your variant 1:

``````colors <- sapply(a\$b, function(x) if(x < 5) "red" else if(a\$d[x] %in% e\$a.d.3.15.) "blue" else "black")
plot(a\$b, a\$c, col=colors)
``````

Your previous if/else argument was not looping through your data. `if(a\$b < 5)` was only looking at the first argument of your vector.