Search code examples
rggplot2axis-labels

Move only some x axis labels down in ggplot


See this plot:

tibble(x = 0:10, y = rnorm(11)) %>%
  ggplot(aes(x,y)) +
  geom_point() +
  scale_x_continuous(breaks = c(seq(0,10,2)/10, seq(2,10,1)))

enter image description here

The labels in the beginning of the axis are very crowded. Is there a way to push down only some labels (e.g. those of c(0.2, 0.6, 0.8)) so that all labels would be readable? Bonus: add a vertical line from ticks to those labels which have been pushed down (in other words make the tick longer).

I know I can use vjust = -5 as in + theme(axis.text.x = element_text(vjust = -5)) but that would push down all labels.


Solution

  • This is how to do it the hard way, if you really want those long ticks

    tibble(x = 0:10, y = rnorm(11)) %>%
      ggplot(aes(x,y)) +
      geom_vline(xintercept = seq(2, 10, 4)/10, color = "white", size = 0.5) +
      geom_point() +
      scale_x_continuous(breaks = c(seq(0,10,4)/10, seq(2,10,1))) +
      coord_cartesian(clip = "off", ylim = c(-2, 2)) +
      annotate("text", label = format(seq(2, 10, 4)/10, nsmall = 1),
               x = seq(2, 10, 4)/10, y = -2.4,
               size = 3) +
      annotate("segment", x = seq(2, 10, 4)/10, xend = seq(2, 10, 4)/10,
               y = -2.33, yend = -2.2, size = 0.2) +
      theme(axis.text = element_text(color = "black"))
    

    enter image description here