2012-08-01 88 views
9

我需要找到一種方法來以與參考線本身相同的角度註釋參考線。如何以與參考線本身相同的角度註釋參考線?

以下語句將生成參考線和其上方的標籤。然而,線的斜率可能會改變,我需要找到一種方法確保註釋總是處於相同的角度。

plot(1:10,1:10) 
abline(a=8, b=-1) 
text(x=4, y=5, "reference line label", srt=-28) 

enter image description here

有一個簡單的方法來做到這一點R中? 預先感謝

回答

13

的一種方式是使用指定的asp設置積縱橫比,使用asp參數,然後計算出角度:

asp <- 2 

plot(1:10,1:10, asp=asp) 
abline(a=8, b=-1) 
text(x=4, y=5, "reference line label", srt=180/pi*atan(-1*asp)) 

abline(a=4, b=-2) 
text(x=1, y=3, "reference line label", srt=180/pi*atan(-2*asp)) 

enter image description here

設置不同asp

asp <- 0.8 

plot(1:10,1:10, asp=asp) 
abline(a=8, b=-1) 
text(x=4, y=5, "reference line label", srt=180/pi*atan(-1*asp)) 

abline(a=4, b=-2) 
text(x=1, y=3, "reference line label", srt=180/pi*atan(-2*asp)) 

enter image description here

3

ggplot2

data <- data.frame(x = 1:10, y = 1:10) 
intercept <- 10 
slope <- -1 
ggplot(data, aes(x,y)) + geom_point(shape=1) + 
    geom_abline(intercept = intercept, slope = slope) + 
    geom_text(x=4, y=5, label="my label", angle=atan(slope)*180/pi) 

with slope 1

intercept <- 10 
slope <- -2 
ggplot(data, aes(x,y)) + geom_point(shape=1) + 
    geom_abline(intercept = intercept, slope = slope) + 
    geom_text(x=4, y=5, label="my label", angle=atan(slope)*180/pi) 

with slope 2

+0

我嘗試過類似的解決方案,但無法得到它的工作。僅供參考,您的代碼在我的機器上不起作用 - 標籤沒有與生產線相同的斜率。 – Andrie 2012-08-01 21:26:08

+0

Andrie,這個答案不會錯過你關於長寬比的觀點嗎? – 2012-08-01 21:27:48

+0

我沒有在兩個圖中調整標籤的實際位置,但角度與參考線正確匹配。 – Maiasaura 2012-08-01 21:32:43

8

的增編類似的解決方案,以@ Andrie的回答是:即使你不用手動設置par("asp"),可以恢復目前的工作寬高比具有以下功能:

getCurrentAspect <- function() { 
    uy <- diff(grconvertY(1:2,"user","inches")) 
    ux <- diff(grconvertX(1:2,"user","inches")) 
    uy/ux 
} 

所以你可以創建你的情節:set asp <- getCurrentAspect();並繼續@ Andrie的解決方案。

據我所知,這個功能某處在R生態系統的存在,但我還沒有看到它......

+0

啊,謝謝。我用'par(「usr」)'拖了五分鐘,但找不到任何有用的東西。 – Andrie 2012-08-01 21:33:34

+0

非常感謝!我希望有一種方法可以避免計算角度,但這也可以工作。謝謝 – 2012-08-01 21:37:17