2016-09-07 90 views
1

我想用annotate来标记一条直线段。但是,将注释的角度设置为线的斜率不会将注释与线段对齐。ggplot2:为什么我的文本注释不正确?

library(ggplot2) 

ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + 
    stat_function(fun = function(x) { 
    14 - x 
    }, geom = "line") + 
    theme_bw() + 
    annotate(
    geom = "text", 
    x = 7.5, y = 7.5, 
    label = "x + y = 14", 
    angle = -45) # NISTunits::NISTradianTOdeg(atan(-1)) 

这给:

enter image description here

有人能帮助解释这种现象,如何解决这个问题,即对齐标注有相同的角度线段?

+3

由于X轴不具有相同的长度为Y轴。因此,角度不是45!如果两个轴具有相同的比例,它将100%起作用 – Kabulan0lak

+0

@ Kabulan0lak太好了,这很有道理 - 所以建议我应该将视角的纵横比乘以角度?我怎么能以编程的方式做到这一点? – tchakravarty

+1

视图是否有固定大小?如果是这样,你可以计算x轴和y轴之间的比例以得到正确的角度。 – Kabulan0lak

回答

2

我相信这应该会给你你想要的。请参阅此答案以参考Get width of plot area in ggplot2

#Plot so we can reference the viewport 
ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + 
    stat_function(fun = function(x) { 
    14 - x 
    }, geom = "line") 

#Get the currentVPtree and then convert the VP's height/width to inches 
current.vpTree() 
a <- convertWidth(unit(1,'npc'), 'inch', TRUE) 
b <- convertHeight(unit(1,'npc'), 'inch', TRUE) 

#Replot using the ratio of a/b to get the appropriate angle 
ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + 
    stat_function(fun = function(x) { 
    14 - x 
    }, geom = "line") + 
    theme_bw()+ 
    annotate(
    geom = "text", 
    x = 7.5, y = 7.5, 
    label = "x + y = 14", 
    angle = (atan(a/b) * 180/pi) + 270) 

我们基本上得到视口的宽度/高度,然后用简单的几何体(反正切,因为我们有三角形的两边)来计算该行的实际角度是什么。

结果:

enter image description here

+0

对我来说似乎很好......你认为它的哪个方向歪斜? –

相关问题