简体   繁体   中英

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

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 分散

However, trying

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

Gives

坏

or doing lines on y<2.5 which gives

在此输入图像描述

instead of the solution I am after, which is

在此输入图像描述

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!

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)
}

在此输入图像描述

Here is a vectorized solution. It is partly based on the answers to this question with the main difference that the function plotted there is a smooth function, unlike this one. This makes a difference when computing the points to plot and their colors.

fun <- function(x) abs(6 - x)

x <- 1:11
y <- fun(x)
X <- c(x, x + 11)
Y <- c(y, y)
n <- length(X)

color <- ifelse((Y[-n] < 2.5) & (Y[-1] < 2.5), 2, 3)

plot(X, Y, col = color, pch = 16)
segments(x0 = X[-n], y0 = Y[-n], 
         x1 = X[-1], y1 = Y[-1],
         col = color, pch = 16)

在此输入图像描述

To remove the points, start with

plot(X, Y, type = "n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM