Search code examples
rggplot2graphboxplotaxis

Removing duplicate top X axis in ggplot plus add axis break


I need to create several boxplots describing my data. I have an annoying X axis which is continuous and I want to keep it true to scale, but at the same time I need an axis break as the gap is very large between the two largest numbers on the X axis.

So far (very simplified) I have something like this:

library(ggplot2)
library(ggbreak)

yrs<-c("2", "8", "17", "21", "24","64")
df <- data.frame(treatm = factor(rep(c("A", "B"), each = 18)), 
                 seeds = (c(sample.int(1000, 36, replace = TRUE))),
                 years= as.numeric(rep(yrs), each = 6))

ggplot(df, aes(x = years, y = seeds, fill = treatm, group= interaction(years,treatm))) + 
  geom_boxplot() +
  scale_x_continuous(breaks = c(2,8,17,21,24,64),
                     labels = paste0(yrs))+
  scale_x_break(c(26, 62)) +
  theme_classic()

which creates ugly graph

ggbreak is the only way I have managed to create a break in the X axis, but of course the result is far from optimal. Most importantly, I need to remove the strange X axis which appears on top! Optimally, I would like to include some sort of axis break symbol on the axis, like a little zigzag or two dashes or something. Currently I'm finishing up the graphs in Photoshop but that is an enormous waste of time so please help!!


Solution

  • To hide the top x axis you can add the following line :

    theme(axis.text.x.top = element_blank(),
            axis.ticks.x.top = element_blank(),
            axis.line.x.top = element_blank())
    

    To include an axis break symbol, the only "solution" I see is to manually place a tag (// or ... for example) in your graph.

    labs(tag = "//") +
    theme(plot.tag.position = c(0.9, 0.1))
    

    The two parameters of the tag position are values between 0 and 1. They vary depending on the size of your output image so you have adjust it yourself.

    My solution applied to your example gives the following code :

    library(ggplot2)
    library(ggbreak)
    
    yrs<-c("2", "8", "17", "21", "24","64")
    df <- data.frame(treatm = factor(rep(c("A", "B"), each = 18)), 
                     seeds = (c(sample.int(1000, 36, replace = TRUE))),
                     years= as.numeric(rep(yrs), each = 6))
    
    ggplot(df, aes(x = years, y = seeds, fill = treatm, group= interaction(years,treatm))) + 
      geom_boxplot() +
      scale_x_continuous(breaks = c(2,8,17,21,24,64),
                         labels = paste0(yrs))+
      scale_x_break(c(26, 62)) +
      theme_classic()+
      theme(axis.text.x.top = element_blank(),
            axis.ticks.x.top = element_blank(),
            axis.line.x.top = element_blank())+
      labs(tag = "//") +
      theme(plot.tag.position = c(0.767, 0.15)) # <-- manually adjusted parameters