0

I know there are a million questions like this out there, but I'm having trouble finding on that helps me.

Here's a simple reprex:

library(ggplot2)
library(ggpubr)
library(gridExtra)
ex.table <- structure(c(CAT1 = 0, CAT2 = 318, CAT3 = 21, CAT4 = 1897,CAT5 = 301, CAT6 = 643, CAT7 = 770, CAT8 = 120, CAT9 = 43), .Dim = 9L, .Dimnames = list(c("CAT1", "CAT2", "CAT3", "CAT4", "CAT5", "CAT6", "CAT7", "CAT8", "CAT9")))

I plot it:

p <- ggplot() +
  geom_bar(aes(x=names(ex.table), y=ex.table), stat="identity") +
  ylab("Some Number") +
  xlab("") +
  scale_x_discrete(labels=c("Lots of words, \nalmost too many to function with", "Few words", "Fewer but still a few", "Blah", "Blah blah", "Lots of words again \njust because I need more", "The quick brown fox jumps", "Over the", "Lazy dog"))

p + theme(axis.text.x=element_text(angle = 45, hjust=.8, margin = margin(t=25), colour = "black"))

THE QUESTION How do I left-justify the top lines of the multi-line labels (similar to hjust=0), and shift the labels to the left so that the end of the label lines up with the tick mark (similar to hjust=1)...hjust, vjust, and margin are not solving my problems. Can anyone help me finetune these labels?

If I adjust margin, and leave hjust=0, I get labels that are incorrectly aligned but formatted nicely:

p + theme(axis.text.x=element_text(angle = 45, hjust=0, margin=margin(t=100), colour = "black"))

If I adjust hjust, I lose the justification I want, but the position is good:

p + theme(axis.text.x=element_text(angle = 45, hjust=1, colour = "black"))

With this example, if I separate my line breaks differently I can sort of get there, but I want to know how to shift these labels. My ideal output is similar to the last line of code above but with all top-line text left-justified. Can I do it?

Thanks for any help.

Axeman
  • 32,068
  • 8
  • 81
  • 94
NoobR
  • 311
  • 2
  • 10
  • 2
    FYI, I edited your question for code-formatting (triple-backticks versus inline-code single backticks) as well as adding spaces in between commands and commas. While the first one is mostly just SO-style, the second is as much for human-readability and separating components as anything. It is a personal preference I think is shared among many, but if you disagree then feel free to roll back my edit. (SO-markdown help: https://stackoverflow.com/editing-help#syntax-highlighting) – r2evans Jan 16 '20 at 17:40
  • 1
    That works for me. Thanks. – NoobR Jan 16 '20 at 18:25
  • Just a partial suggestion, but you could see about using some combination of clever line breaks and adjusting the `vjust` for individual labels as in this example: https://stackoverflow.com/questions/48286116/justify-individual-axis-labels-in-bold-using-ggplot2 – Fragilaria Jan 16 '20 at 18:26
  • I did end up going with creative spacing and line breaks. Still curious if there's a more direct function. – NoobR Jan 23 '20 at 17:14

0 Answers0