ggplot2
automatically centers the text in a geom_text
layer. For example:
library(ggplot2)
library(tidyverse)
df <- data_frame(text = c("A short sentence.",
"A slightly longer sentence.",
"This sentence is the longest of the sentences."),
y = row_number(text) - 1,
x = 1)
ggplot(df, aes(x = x, y = y)) +
geom_text(aes(label = text), nudge_x = nchar(text)/2)
Produces:
ggplot:
However, I want to left-justify the text in a neat column. I'm essentially asking how to provide an xmin
to the text
. Do I need to perform a mathematical operation on the x
variable that scales x
accordingly? Or is there a trick with theme
?
You can use hjust
:
ggplot(df, aes(x = x, y = y)) +
geom_text(aes(label = text), hjust = 0)
You can also add an xlim
to align the column to the very left side of the plot:
ggplot(df, aes(x = x, y = y)) +
geom_text(aes(label = text), hjust = 0) + xlim(1, 1.5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With