Ahdee
Ahdee

Reputation: 4949

Plot color based on value of y in R

Hi I would like to plot with different color based value (eg < 0). I found a solution on a previous post but when I tried to duplicate it failed.

plot(-10:10,
     type="o", 
     pch = 19,
     col = ifelse(x < 0,'red','green'),
     xaxt = "n",
)

I also tried this but did not work as well.

plot(-10:10,
     type="o", 
     pch = 19,
     col = if(x < 0){'red'} else{'green'},
     xaxt = "n",
)

When I do the above, all I get is green; reversing from < to > makes everything red, so it treats all the value as > 0. Thanks in advance.

Upvotes: 1

Views: 92

Answers (3)

Steven Beaupr&#233;
Steven Beaupr&#233;

Reputation: 21621

Since you asked for a "black" line and coloured dots in the comments, try:

x=-10:10
plot(x, type = "l"); points(x, pch = 19, col = ifelse(x < 0, 'red', 'green'))

enter image description here

Upvotes: 1

S&#246;lvi
S&#246;lvi

Reputation: 520

The plot function does not know what x is in your example. This works:

x=-10:10
plot(x,pch=19,type="o",col=ifelse(x<0,'red','green'))

Hope this helps!

Upvotes: 2

sgibb
sgibb

Reputation: 25726

You have to define x before:

x <- -10:10
plot(x, type="o", pch = 19, col = ifelse(x < 0,'red','green'))

enter image description here

Upvotes: 1

Related Questions