Seymour
Seymour

Reputation: 3264

Left-align X-axis label with first tick text on X-axis

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?

The result should look like: enter image description here

I am looking for a solution that can be easily generalized to other plots.

Upvotes: 3

Views: 1195

Answers (1)

akrun
akrun

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))

enter image description here

Upvotes: 6

Related Questions