I need to find a way to annotate a reference line at the same angle as the reference line itself.
The following statement will produce the reference line and the la
Working example for ggplot2:
slope<-1.3
asp<-1
p <- ggplot()
p<-p+scale_x_continuous(limits = c(1, 15), expand = c(0, 0))
p<-p+scale_y_continuous(limits = c(-8, 20), expand = c(0, 0))
p<-p+geom_abline(intercept = 0, slope = slope)
p<-p+coord_fixed(asp)
p<-p+annotate("text", label = "reference line label", x = 3.5, y = 5, colour = "red",angle=atan(slope*asp)*180/pi)
p
text with angle:
A similar solution with 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)
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)
One way is by setting the plot aspect ratio, using the asp
argument, and then to calculate the angles using the specified 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))
Setting a different 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))
An addendum to @Andrie's answer: instead of hard-coding the aspect ratio in the plot the first time to get the relative coordinate scales, you can recover the current working aspect ratio with the following function:
getCurrentAspect <- function() {
uy <- diff(grconvertY(1:2,"user","inches"))
ux <- diff(grconvertX(1:2,"user","inches"))
uy/ux
}
So you can create your plot: set asp <- getCurrentAspect()
; and proceed with the rest of @Andrie's solution.
For all I know this function exists somewhere in the R ecosystem, but I haven't seen it ...