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.