r - ggplot2: Why are my text annotations not aligned right? -
i trying label straight line segment using annotate
. however, setting angle of annotation slope of line not align annotation line segment.
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))
this gives:
can explain phenomenon, , how fix this, i.e., align annotation have same angle line segment?
i believe should give want. see answer reference get width of plot area in ggplot2.
#plot can reference viewport ggplot(data.frame(x = seq(0, 14, 0.1)), aes(x = x)) + stat_function(fun = function(x) { 14 - x }, geom = "line") #get currentvptree , convert vp's height/width inches current.vptree() <- convertwidth(unit(1,'npc'), 'inch', true) b <- convertheight(unit(1,'npc'), 'inch', true) #replot using ratio of a/b 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)
we viewport width/height , use simple geometry (inverse tangent since have both sides of triangle) calculate actual angle of line is.
result:
Comments
Post a Comment