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"
)
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)
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
)
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.