Reputation: 4949
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
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'))
Upvotes: 1
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
Reputation: 25726
You have to define x
before:
x <- -10:10
plot(x, type="o", pch = 19, col = ifelse(x < 0,'red','green'))
Upvotes: 1