Left justify text from multi-line facet labels

This is fairly straightforward using grid's grid.gedit function to edit the strips.

library(ggplot2)  # v2.1.0
library(grid)

# Your data
set.seed(3)
df = data.frame(facet_label_text = rep(c("Label A",
                                         "Label B\nvery long label",
                                         "Label C\nshort",
                                         "Label D"), 
                                       each = 5),
                time = rep(c(0, 4, 8, 12, 16), times = 4),
                value = runif(20, min=0, max=100))

# Your plot
p = ggplot(df, aes(x = time, y = value)) +
    geom_line() +
    facet_grid(facet_label_text ~ .) +
    theme(strip.text.y = element_text(angle = 0, hjust = 0))
p

# Get a list of grobs in the plot
grid.ls(grid.force())  

# It looks like we need the GRID.text grobs.
# But some care is needed:
# There are GRID.text grobs that are children of the strips;
# but also there are GRID.text grobs that are children of the axes.
# Therefore, a gPath should be set up 
# to get to the GRID.text grobs in the strips

# The edit
grid.gedit(gPath("GRID.stripGrob", "GRID.text"),  
         just = "left", x = unit(0, "npc"))

Or, a few more lines of code to work with a grob object (in place of editing on screen as above):

# Get the ggplot grob
gp = ggplotGrob(p)
grid.ls(grid.force(gp))

# Edit the grob
gp = editGrob(grid.force(gp), gPath("GRID.stripGrob", "GRID.text"), grep = TRUE, global = TRUE,
          just = "left", x = unit(0, "npc"))

# Draw it
grid.newpage()
grid.draw(gp)

enter image description here


Until someone comes along with a real solution, here's a hack: Add space in the labels to get the justification you want.

require(ggplot2)

#Generate example data
set.seed(3)
df = data.frame(facet_label_text = rep(c("Label A",
                                         "Label B           \nvery long label",
                                         "Label C\nshort     ",
                                         "Label D"),
                                       each = 5),
                time = rep(c(0, 4, 8, 12, 16), times = 4),
                value = runif(20, min=0, max=100))

#Plot test data
ggplot(df, aes(x = time, y = value)) +
  geom_line() +
  facet_grid(facet_label_text ~ .) +
  theme(strip.text.y = element_text(angle = 0, hjust = 0))

enter image description here

Tags:

R

Ggplot2