1

I'm having some trouble aligning axis labels across facets in ggplot. I'm trying to left align all of the y-axis labels to make the text look more uniform, but the moment the "scales = free" argument is added to the script, the labels only become aligned within the facet. I've tested with some dummy code and the same issue occurs:

test <- data.frame(label = c('a', 'ab', 'a', 'abc', 'abcd', 'abcde', 
                             'abcdef', 'abcdefg', 'abcdefgh', 
                             'abcdefghi', 'abcdefghij', 
                             'abcdefghijkfiutdkjgbhcvi'),
                   xdum = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
                   facett = rep(c("Facet 1", "Facet 2", "Facet 3"), 4), 
                   data = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))

ggplot(test, aes(x = xdum, y = label, label = data)) + 
  facet_grid(facett~., scales = "free", space = "free") + 
  geom_tile() + 
  theme(axis.ticks = element_blank(), axis.text.y = element_text(hjust = 0))

Has anyone seen this before and found a workaround or will I have to mess around with the gtable code?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
addfunr3
  • 48
  • 6
  • 1
    Have you considered `axis.text.y = element_text(hjust = 1)` ? This preserves alignment and right-aligned text can look better with the long labels. – neilfws Jan 31 '18 at 03:39
  • 2
    That works no problem and DOES look neater, but my customer wants it to be left aligned... – addfunr3 Jan 31 '18 at 03:48

1 Answers1

5

You can pad the labels out to the length of the longest string and then display them in a fixed-width font:

max_width = max(nchar(as.character(test$label)))
test$label_padded = sprintf(paste0("%-", max_width, "s"), test$label)

# (Ignore this if not on Windows)
windowsFonts(Consolas = "Consolas")
ggplot(test, aes(x = xdum, y = label_padded, label = data)) + 
    facet_grid(facett~., scales = "free", space = "free") + 
    geom_tile() + 
    theme(axis.ticks = element_blank(), 
          axis.text.y = element_text(hjust = 0, family = "Consolas"))

enter image description here

Marius
  • 58,213
  • 16
  • 107
  • 105
  • Thank Marius! I had tested padding the labels with spaces, but had no idea about the fixed-width fonts. – addfunr3 Jan 31 '18 at 03:59