how to automatically skip some x-labels?

Consider this simple example

tibble(x = c('2001-01',
       y = c(10,20,10,3)) %>% 
  ggplot(aes(x = x, y = y)) + geom_col()

which gives

My issue is that I would like to skip every other label for the x-axis.

For instance, only showing 2001-01 but a blank for 2001-02, then showing 2001-03 and then a blank for 2001-04. Nevertheless, I would still like to see a tick for all of them.

How can I do that automatically with ggplot and likely scale_x_discrete?


A simple way is supply the labels manually, and just put "" for the ones you don't want.

df <- your_tibble
xlabels <- sort(unique(df$x))
xlabels[seq(2, length(xlabels), 2)] <- ""

# then use
scale_x_discrete(labels = xlabels)
1 Like

thanks! but is there any way to do it on the fly within the ggplot call?

If you assign the data to some dataframe such as df then you can do it on the fly with a function.


df <- tibble(x = c('2001-01',
       y = c(10,20,10,3)) 

everysecond <- function(x){
  x <- sort(unique(x))
  x[seq(2, length(x), 2)] <- ""

ggplot(data = df) + 
  geom_col(mapping = aes(x = x, y = y)) + 
  scale_x_discrete(labels = everysecond(df$x))

Created on 2020-05-13 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.