I'm looking for a way to automatically move the y-axis tick labels so that they appear left-justified within the actual plot area. I love the general flexibility of theme components in ggplot, but ran into a wall trying to find a general way to do this.
I know giving axis.text.y
a combination of hjust=0
and a negative right margin (*gag*) can accomplish this effect, but the negative margin has to be manually set to match the width of the longest y-axis tick label.
As an example, consider the following code:
library(ggplot2)
set.seed(0)
dat <- data.frame(x = 1:100, y = (1:100) + runif(100, -10, 10))
p1 <- ggplot(dat, aes(x, y)) +
geom_line() +
scale_y_continuous("", breaks = c(0, 30, 60, 90),
labels = c(0, 30, 60, "90 units of something")) +
theme(axis.text.y = element_text(hjust = 0,
margin = margin(0, -3.1, 0, 0, 'cm')))
I think it elegantly incorporates the y-axis label (e.g., "units of something"
) into the body of the plot, but in order to accomplish it, the -3.1
in the last line has to be found manually (by trial and error), which adds insult to injury: not only am I using a negative margin to pull text where it doesn't want to be -- I'm throwing in some arcane, fragile, hard-coded magic number.
Does anyone know where I can look for a more general and elegant solution to this problem?
ggplot(dat, aes(x, y)) + geom_line() + scale_y_continuous("", breaks=c(0, 30, 60, 90)) + annotate("text", x=-Inf, y=c(0, 30, 60, 90), label=c(0, 30, 60, "90 units of something"), hjust=0 )+ theme(axis.text.y = element_blank())
– user20650