Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colour a line by a given value in a plot in R

Tags:

Advancing on the answer given here where the same question was asked for a scatter plot, is it possible to plot a line where the colour is based on the y value?

Example data

x = 1:11
y = abs(6 - x)
plot(1:22,c(y,y), col = ifelse(c(y,y) < 2.5, 2, 3), pch = 16)

Will give scatter

However, trying

plot(1:22,c(y,y), col = ifelse(c(y,y) < 2.5, 2, 3), type = "l")

Gives

bad

or doing lines on y<2.5 which gives

enter image description here

instead of the solution I am after, which is

enter image description here

Is there any easy method to do this? This is only a simple case, and I can't manually add each section to my actual data. Thanks!

like image 494
Beavis Avatar asked Aug 23 '19 10:08

Beavis


People also ask

How do I color a point based on value in R?

To change the color and the size of points, use the following arguments: col : color (hexadecimal color code or color name). For example, col = "blue" or col = "#4F6228" .

How do you color a plot by a variable in R?

One of the ways to add color to scatter plot by a variable is to use color argument inside global aes() function with the variable we want to color with. In this scatter plot we color the points by the origin airport using color=origin. The color argument has added colors to scatterplot with default colors by ggplot2.

What is the function to give color to plot?

R plot() Function (Add Titles, Labels, Change Colors and Overlaying Pots)

How do I change the color of a dot in R?

The following arguments can be used to change the color and the size of the points : col : color (code or name) to use for the points. bg : the background (or fill) color for the open plot symbols. It can be used only when pch = 21:25.


1 Answers

Try this

x = 1:11
y = abs(6 - x)
y = c(y,y)
plot(1:22,y, col = ifelse(c(y,y) < 2.5, 2, 3), pch = 16)



for(i in 1:21){
  if(y[i]>1.9&& y[i+1]>1.9){
    linecolour="green"
  } else {
    linecolour="red"
  }
  lines(c((1:22)[i],(1:22)[i+1]),c(y[i],y[i+1]),col=linecolour)
}

enter image description here

like image 188
Daniel O Avatar answered Oct 11 '22 17:10

Daniel O