How to align multiline text annotation in ggplot

I'd like to figure out how to left justify the following multiline text element within a ggplot2 plot:

library(tidyverse)
tibble(x = 1, y = 1) %>% 
  ggplot(aes(x, y)) +
  geom_text(
    label =
      "line 1 is this long
    line 2 is longer than line 2
    line 3 is short"
  )

Created on 2021-03-25 by the reprex package (v0.3.0)

Although I've been able to alter the relative alignment between the lines in various ways (for example, by inserting spaces or using paste()), I haven't been able to left justify them.

Any non-hacky solution would be welcome, whether or not it uses geom_text()!

I used hjust and formatted the code in an ugly way to make sure there were no unwanted spaces.

library(tibble)
library(ggplot2)
tibble(x = 1, y = 1) %>% 
  ggplot(aes(x, y)) + 
  geom_text(
    label =
"line 1 is this long
line 2 is longer than line 2
line 3 is short", 
hjust = 0)

Created on 2021-03-25 by the reprex package (v0.3.0)

1 Like

Thank you, @FJCC -- my eyes must have glided over that aesthetic in the documentation for geom_text() when I read it earlier.

It is strange how space affects the result when hjust = 0 is omitted, but at least with it, I can use paste() to avoid having to tweak by adding space or removing indentation. For example, here's another failure omits hjust but is an attempt pad the lines to make them equal length:

library(tibble)
library(ggplot2)
tibble(x = 1, y = 1) %>% 
  ggplot(aes(x, y)) + 
  geom_text(
    label =
      paste(
        "line 1 is this long         ",
        "line 2 is longer than line 2",
        "line 3 is short             ", 
        sep = "\n"
      ),
    # hjust = 0
  )

Created on 2021-03-25 by the reprex package (v0.3.0)

I just realized that hjust = 0 didn't just left-justify the text, it also shifted the invisible text box so its left edge is at x = 1. Do you think there a simple way to left justify text within the invisible text box without affecting the placement of the box itself?

I find it easier to think of hjust as determining which part of the text will be placed at the x value passed to geom_text: 0 = left edge, 0.5 = center, 1 = right. To have the three lines of text appear with their left edges aligned and slightly to the left of x = 1, you have to plot them with hjust = 0 and with an x value less than one. I do not know of any other way to do that.

Thanks, @FJCC , I'm curious about separating the two behaviors, so I'll post a follow-up question.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.