Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left-justify geom_text layer with ggplot2

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?

like image 548
David Ranzolin Avatar asked Sep 16 '17 22:09

David Ranzolin


1 Answers

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

like image 68
acylam Avatar answered Oct 18 '22 09:10

acylam