Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a line chart with conditional colors depending on values

Tags:

plot

r

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?

like image 350
Sebastian Avatar asked Sep 08 '11 06:09

Sebastian


People also ask

How do you change graph colors in Excel based on value?

In a chart, click to select the data series for which you want to change the colors. On the Format tab, in the Current Selection group, click Format Selection. tab, expand Fill, and then do one of the following: To vary the colors of data markers in a single-series chart, select the Vary colors by point check box.

How do you change chart colors based on value?

Select the bar chart or column chart, then click Kutools > Charts > Color Chart by Value. Then in the popped-out dialog, set the value range and the relative color as you need. Click to free download now!


1 Answers

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

like image 54
Andrie Avatar answered Sep 22 '22 21:09

Andrie