Reputation: 3264
Considering the following example,
library(ggplot2)
dat <- data.frame(number = c(5, 10, 11 ,12,12,12,13,15,15))
ggplot(dat, aes(x = number)) + geom_histogram()
How can I left-align the label of X-axis in such a way to be aligned with the text of the first tick on X-axis?
Upvotes: 3
Views: 1195
Reputation: 886948
We could get the position of the first tick labels once we create the plot object
p <- ggplot(dat, aes(x = number)) +
geom_histogram()
i1 <- ggplot_build(p)$layout$panel_ranges[[1]]$x.major[1]
#or
library(magrittr)
i1 <- p %>%
ggplot_build %>%
extract2("layout") %>%
extract2("panel_ranges") %>%
extract2(1) %>%
extract2("x.major") %>%
extract(1)
and then use that in theme
. Better would be take a look and adjust if it is necessary
p +
theme(axis.title.x = element_text(hjust = i1- 0.01))
Upvotes: 6