12

I want to plot a line chart. Depending on values it should change its color. What I found is:

plot(sin(seq(from=1, to=10,by=0.1)),type="p", 
       col=ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","yellow"))

That works. But as soon as I change from type="p" to type="l" the conditional colouring disappears.

Is that behavior intended?

What is a solution with base graphics to plot a functional line with different colors?

Andrie
  • 176,377
  • 47
  • 447
  • 496
Sebastian
  • 633
  • 2
  • 6
  • 16

3 Answers3

16

Use segments instead of lines.

The segments function will only add to an existing plot. To create a blank plot with the correct axes and limits, first use plot with type="n" to draw "nothing".

x0 <- seq(1, 10, 0.1)
colour <- ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","blue")

plot(x0, sin(x0), type="n")
segments(x0=x0, y0=sin(x0), x1=x0+0.1, y1=sin(x0+0.1), col=colour)

See ?segments for more detail.

enter image description here

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • When you add `abline(h = 0.5)` you will note that the colors do not change at the indended value. –  Mar 24 '19 at 09:08
9

Here is a little different approach:

x <- seq(from=1, to=10, by=0.1)
plot(x,sin(x), col='red', type='l')
clip(1,10,-1,.5)
lines(x,sin(x), col='yellow', type='l')

enter image description here

Note that with this method the curve changes colors at exactly 0.5.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
1

After you've drawn a line plot, you can color it with segments():

seq1 <- seq(from=1, to=10, by=0.1)
values <- sin(seq1)
s <- seq(length(seq1)-1)
segments(seq1[s], values[s], seq1[s+1], values[s+1], col=ifelse(values > 0.5, "red", "yellow"))

enter image description here

Anatoliy
  • 1,350
  • 9
  • 9
  • It seems that without drawing a line first you'll have to set up all the plot limits and axis yourself, which is tedious. Or maybe I haven't found a way. – Anatoliy Sep 08 '11 at 07:15
  • When you add `abline(h = 0.5)` you will note that the colors do not change at the indended value. –  Mar 24 '19 at 09:08