绘制R

时间:2016-10-24 22:05:32

标签: r plot ggplot2 scatter-plot

我正在学习在R中绘图并寻找为成对点数据添加水平线的方法,如果它们满足基本不等式条件的话。例如,对于给定的输入集,我有3组输出值。

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

enter image description here

但是,我想说明输出值的成对差异。因此,如果i,我想要一条线(黄色)连接每个输入b[i] > a[i]的黑色(a)和红色(b)点,而不是散点图。同样地,如果c[i] > b[i],我还有另一条线(蓝色)连接红色(b)和绿色(c)点。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以通过逻辑判断ifsegments()来执行此操作。 sapply(input, function(...))为每个function应用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)

enter image description here

答案 1 :(得分:1)

试试这个:

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

enter image description here