2016-10-24 62 views
0

我正在學習如何繪製R並尋找方法爲成對點數據添加水平線,條件是它們滿足基本不等式條件。例如,對於給定的一組輸入,我有3組輸出值。繪製R中成對點的水平線

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

不過,我想說明的輸出值的配對差異。因此,如果b[i] > a[i],而不是散點圖,我想要連接黑色(a)和紅色(b)點的線條(黃色)用於每個輸入i。同樣,如果c[i] > b[i]有連接紅(b)和綠(c)點的另一條線(藍色)。

我該怎麼做?

回答

1

您可以通過邏輯判斷,ifsegments()來做到這一點。 sapply(input, function(...))適用於每個inputfunction

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

試試這個簡單的:

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