gregmacfarlane
gregmacfarlane

Reputation: 2283

Staggered axis labels in ggplot2

I wanted to stagger my x-axis labels in ggplot2. Amazingly, the thing I tried worked (thanks to @Hadley and the consistent grammar!).

c <- ggplot(mtcars, aes(factor(cyl)))
c <- c + geom_bar()
c + theme(axis.text.x = element_text(vjust = c(0, 0.1, 0.2)))

Too much whitespace!

But it seems that as a consequence, the amount of vertical space dedicated to the margin became unnecessarily large. Any tips on getting this back down to size?

Upvotes: 5

Views: 1426

Answers (1)

BrodieG
BrodieG

Reputation: 52637

Not entirely sure what's going on, but here is a potential work-around:

c + theme(axis.text.x = element_text(vjust = grid::unit(c(-2, 0, 2), "points")))

For some reason the default units of npc which are fractions of the containing element size are not working right when you use a greater than one length vjust vector. I also suspect vjust was not fully intended to work with longer than one vectors (not sure).

enter image description here

Upvotes: 5

Related Questions