I'm plotting 2 densities and trying to add a few annotations that align horizontally while text is rotated 90 degrees but I can't seem to get them to line up when the annotations are of different character lengths.
library(ggplot2)
n <- 10000
mu_a <- .089
mu_b <- .099
s_a <- .0092
s_b <- .004
df <- data.frame(
variant = factor(c(rep("A", n),rep("B", n))),
p = c(rnorm(n = n, mean = mu_a, sd = s_a), rnorm(n = n, mean = mu_b, sd = s_b)))
ggplot(df, aes(x = p, fill = variant)) +
geom_density() +
scale_x_continuous(labels = scales::percent) +
scale_y_continuous(expand = expansion(mult = c(0, .1))) +
annotate("text",
x = c(mu_a,mu_b),
y = Inf,
vjust = "center",
hjust = 6,
label = c("5char","06char"),
angle = 90
)
Created on 2021-05-12 by the reprex package (v0.3.0)
Plot image at https://i.stack.imgur.com/89PjI.png
I've tried changing the y axis to a 0:1 scale with scale_y_continuous(y = ..scaled..)
and then setting the annotation y values to fixed positions like y = 0.2
but then the densities aren't sized appropriately. Have tried all manner of combinations of hjust and vjust. I thought that these were supposed to work like percentages of the plot. So vjust = 0.2
means 20% up the plot, but it's not working like that for me. I was not expecting that by rotating the text 90 degrees, that hjust and vjust would swap, but that seems to be what happened.