简体   繁体   中英

Plot horizontal lines for pairwise points in R

I'm learning to plot in R and looking for ways to add horizontal lines for pairwise point data if they satisfy basic inequality condition. For example, I have 3 sets of output values for a given set of input.

input <- c(1,2,3,4)
a <- c(1,2,3,4)
b <- c(2,3,4,5)
c <- c(5,6,7,3)
plot(a, input, xlim=c(min(a,b,c), max(a,b,c)), pch=16, col=rgb(0,0,0,0.5), xlab='output', ylab='input')
points(b, input, pch=16, col=rgb(1,0,0,0.5))
points(c, input, pch=16, col=rgb(0,1,0,0.5))

在此处输入图片说明

However, I want to illustrate the pairwise differences in the output values. So, instead of a scatter plot, I want a line (yellow) connecting the black (a) and red (b) dots for each input i if b[i] > a[i] . Similarly, I'd have another line (blue) connecting the red (b) and green (c) dots if c[i] > b[i] .

How would I do that?

You can do it by logical judgement, if , and segments() . sapply(input, function(...)) applies function for each input .

plot(a, input, xlim=c(min(a,b,c), max(a,b,c)), pch=16, col=rgb(0,0,0,0.5), xlab='output', ylab='input')
points(b, input, pch=16, col=rgb(1,0,0,0.5))
points(c, input, pch=16, col=rgb(0,1,0,0.5))

sapply(input, function(x, a, b, c) {
  if(b[x] > a[x]) segments(a[x], x, b[x], x, col = "yellow3")
  if(c[x] > b[x]) segments(b[x], x, c[x], x, col = "blue")
  }, a = a, b = b, c = c)

在此处输入图片说明

Try this simply:

indices <- which(b > a)
segments(a[indices], input[indices], b[indices], input[indices], col='yellow')
indices <- which(c > b)
segments(b[indices], input[indices], c[indices], input[indices], col='blue')

在此处输入图片说明

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