Search code examples
rggplot2boxplot

Show 1 centered x-tick with label with even (4) discrete groups


Im a bit surprissed I couldnt find the answer...but I have a boxplot with four groups but want to show 1 centerd tick on the x-axis on position 2.5....how do I do that?

library(ggplot2)

# Create a sample dataset
group <- rep(c("Group 1", "Group 2", "Group 3", "Group 4"), each = 10)
value <- rnorm(40)
data <- data.frame(group, value)

# Create the boxplot with a single x-tick
ggplot(data, aes(x = group, y = value, fill = group)) +
  geom_boxplot() +
  scale_x_discrete(labels = "test", breaks = 2.5) +
  labs(x = "", y = "Value") +
  ggtitle("Boxplot with a Single X-Tick") 

Solution

  • The simplest solution here is to plot all the boxes at the fictional x position 'test', and use position_dodge:

    ggplot(data, aes(x = 'test', y = value, fill = group)) +
      geom_boxplot(position = position_dodge(width = 1)) +
      labs(x = "", y = "Value") +
      ggtitle("Boxplot with a Single X-Tick") 
    

    enter image description here

    An alternative that may be a little more flexible is to use custom annotations:

    ggplot(data, aes(x = group, y = value, fill = group)) +
      geom_boxplot() +
      scale_x_discrete(labels = "test", breaks = 2.5) +
      labs(x = "", y = "Value") +
      coord_cartesian(clip = 'off') +
      annotation_custom(grid::linesGrob(x = c(0.5, 0.5), y = c(-0.01, 0))) +
      annotation_custom(grid::textGrob('test', x = 0.5, y = -0.03)) +
      ggtitle("Boxplot with a Single X-Tick") 
    

    enter image description here