Hi all! I'm trying to align an annotation with an abline, but can't figure out how to determine the correct annotation angle. I'd prefer to set the annotation angle using the abline slope, but I'm instead required to use an angle. I believe that this angle is dependent on the abline slope and the limits and dimensions of the plot, making it tricky.
How can I get the annotation to line up with the abline without hard-coding the angle? Thanks for any suggestions!
library(tidyverse)
test_data <- tribble(
~x, ~y,
0, 1,
1, 0,
4, 1
)
my_slope <- 1/3
# angles don't line up due to coord limits
test_data %>%
ggplot(aes(x, y)) +
geom_abline(intercept = 0, slope = my_slope) +
geom_point() +
annotate(
"text",
x = 2,
y = 2 * my_slope,
angle = atan(my_slope) * 180/pi,
label = "my line"
)
# line and text line up, but with incorrect coordinate limits
test_data %>%
ggplot(aes(x, y)) +
geom_abline(intercept = 0, slope = my_slope) +
geom_point() +
annotate(
"text",
x = 2,
y = 2 * my_slope * 1.1,
angle = atan(my_slope) * 180/pi,
label = "my line"
) +
coord_equal()
# I set angle manually, which is error-prone
test_data %>%
ggplot(aes(x, y)) +
geom_abline(intercept = 0, slope = my_slope) +
geom_point() +
annotate(
"text",
x = 2,
y = 2 * my_slope * 1.1,
angle = 37,
label = "my line"
)
Created on 2019-03-17 by the reprex package (v0.2.1)