Home > Mobile >  Move only some x axis labels down in ggplot
Move only some x axis labels down in ggplot

Time:03-30

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.

CodePudding user response:

Here is a very simple method that pushes down the axis text by adding a new line character \n before the label in the vector x_ticks.

library(tidyverse)
x_ticks <- c(seq(0,10,2)/10, seq(2,10,1))

tibble(x = 0:10, y = rnorm(11)) %>%
  ggplot(aes(x,y))  
  geom_point()  
  scale_x_continuous(breaks = x_ticks, 
                     labels = ifelse(x_ticks %in% c(0.2, 0.6, 0.8), 
                                     paste0("\n", x_ticks), x_ticks))

Created on 2022-03-30 by the enter image description here

  • Related