How do I set an `xmin` argument to `geom_text`?

ggplot2

#1

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?


#2

I may be missing something more complicated that you wanted (I couldn’t get the nudge_x argument to work as written, and I’m not sure if you intended it to be in your example). That said, is there a reason not to use the hjust argument for geom_text? You may want to change the limits of the graph, but it does line them up on the left as I think you wanted.

ggplot(df, aes(x = x, y = y)) +
  geom_text(aes(label = text), hjust = "left")


#3

Thanks Nick, that’s perfect! I knew there was a simple solution somewhere.


#4

see also https://stackoverflow.com/q/46259140/471093