Left-justify geom_text layer with ggplot2

19.8k views Asked by At

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:

link to ggplot (I'm not allowed to post images yet)

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?

1

There are 1 answers

0
acylam On BEST ANSWER

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)

enter image description here