2012-08-01 25 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