R ggplot2:为什么我的文本注释没有对齐?

R ggplot2:为什么我的文本注释没有对齐?,r,ggplot2,R,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 =

我正在尝试使用
注释
标记直线段。但是,将注释的角度设置为直线的坡度不会将注释与线段对齐

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))
这使得:


是否有人可以帮助解释此现象,以及如何解决此问题,即对齐注释使其与线段具有相同的角度

我相信这会给你想要的。请参阅此答案以供参考

#打印以便我们可以参考视口
ggplot(数据帧(x=seq(0,14,0.1)),aes(x=x))+
stat_函数(fun=函数(x){
14-x
},geom=“line”)
#获取当前VPtree,然后将VP的高度/宽度转换为英寸
current.vpTree()

a因为x轴的长度与y轴的长度不同。因此,角度不是45!如果两个轴具有相同的比例,它将100%@Kabulan0lak很棒,这是有意义的——因此建议我将角度乘以视口的纵横比?我如何通过编程实现这一点?视图的大小是否固定?如果是这样,您可以计算x轴和y轴之间的比率以获得适当的角度,是。@Kabulan0lak否,视口没有固定的纵横比。您可以只添加
coord_fixed()
,以便纵横比是固定的……当尝试将文本坡度与绘图中的其他元素匹配时,添加
+coord_fixed(a/b)会很有帮助
设置纵横比,否则文本的角度可能会改变,例如,如果将打印输出为图像或添加/更改图例。
#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)