2014-06-24 38 views
1

我無法理解基礎圖形中的段函數在我的特定問題的上下文中。具有間隔的R段函數

x <- 0:1000 
y <- c(0, 40000, 80000) 

現在我想畫一條線,從0到200在y = 0的一條線。在y = 40000時從200到500的另一行和在y = 80000時從500到1000的最後一行。

plot(x,y,type="n") 
segments(0,0,200,40000,200,40000,500,8000,1000) 
points(0,0,200,40000,200,40000,500,8000,1000) 
points(0,0,200,40000,200,40000,500,8000,1000) 

我相信在這裏定義確切的段是錯誤的。如果x 0:3我會知道該怎麼做。但是在間隔的情況下我需要做些什麼?

+1

嗯,首先你的'圖()'調用沒有按'x'和'y'有不同的長度。其次,你將多個參數傳遞給'segments',其中,如果你閱讀'?segments',你會注意到它需要*向量*的座標爲'x0'和'y0'和'x1'和'y1',它們是x和y座標分別繪製和繪製。你的'segments()'和'points()'調用顯然是錯誤的。 –

回答

2

您需要提供向量座標x0y0x1y1這是x和y座標,以借鑑和分別。考慮下面的工作例如:

x <- seq(0, 1000, length = 200) 
y <- seq(0, 80000, length = 200) 
plot(x,y,type="n") 

from.x <- c(0, 200, 500) 
to.x <- c(200, 500, 1000) 
to.y <- from.y <- c(0, 40000, 80000) # from and to y coords the same 

segments(x0 = from.x, y0 = from.y, x1 = to.x, y1 = to.y) 

這將產生以下情節

enter image description here

+0

非常感謝! – user3347232

0

快速ggplot版本:

library(ggplot2) 
x <- seq(0, 1000, length = 200) 
y <- seq(0, 80000, length = 200) 
plot(x,y,type="n") 

dta <- data.frame(x= from.x,y=from.y, xend=to.x, yend=to.y) 
ggplot(dta, aes(x=x, y=y, xend=xend, yend=yend)) + 
    geom_segment()+ 
    geom_point(shape=16, size=4) + 
    geom_point(aes(x=xend, y=yend), shape=1, size=4)