Text alignment in label right put specify position left

Viewed 609

I am annotating my plot with annotate and I'd like to have the text right aligned, but specify the position of the label as if it would be left aligned.

Here a reproducible example and what I tried:

library(ggplot2)
library(stringr)

mydf <- data.frame(x = 0:15, 
                   y = seq(0, 0.75, 0.05))


text1 <- "first vs. five: 1.456"
text2 <- "second vs. \u2265 six long: 1.567"
text3 <- "third number: 123"

annotations <- str_c(c(text1, text2, text3), collapse = "\n")

ggplot(mydf, aes(x, y)) +
  geom_point() +
  annotate(geom = "label", x = 0.5, y = 0.975, 
           label = annotations, 
           hjust = "left", vjust = "top", size = 4.5)

This gives the correct specification of the position of the label, but not the correct alignment of text:

enter image description here

I tried to fix the alignment with the following, but that doesn't work:

text1_long <- str_pad(text1, width = str_length(text2), side = "left", pad = " ")
text3_long <- str_pad(text3, width = str_length(text2), side = "left", pad = " ")

annotations_long <- str_c(c(text1_long, text2, text3_long), collapse = "\n")

ggplot(mydf, aes(x, y)) +
  geom_point() +
  annotate(geom = "label", x = 0.5, y = 0.975, 
           label = annotations_long, 
           hjust = "left", vjust = "top", size = 4.5)

enter image description here

I know I can do the following, but then I have to specify the x-position of the label differently. Which I don't want to do.

ggplot(mydf, aes(x, y)) +
  geom_point() +
  annotate(geom = "label", x = 10, y = 0.975, 
           label = annotations, 
           hjust = "right", vjust = "top", size = 4.5)

enter image description here

Is there a way to either calculate the x-position, such that I can be sure the label is fixed as x = 0.5 or can I separate the alignment of the text and the label position?

0 Answers
Related