Search code examples
rggplot2axis-labels

Center x-axis labels in grouped violin/boxplot


I am creating violin plots by groups. I would like to label each group using a Greek letter centered at the middle point of each group of violin plots. How can I do this?

So far, I am using scale_x_discrete, but I cannot indicate any sort of centering.

library(ggplot2)
dat <- matrix(rnorm(100*12),ncol=12)

# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)

mat$variable_grouping <- ifelse(mat$variable %in% c('X1', 'X2', 'X3','X4'), 'g1',
                                ifelse(mat$variable %in% c('X5','X6','X7','X8'), 
                                       'g2', 'g3'))

pp <- ggplot(mat, aes(x = variable, y = value, fill = variable_grouping)) + 
  geom_violin(scale="width",adjust = 1,width = 0.5) + 
  scale_x_discrete(labels = c(expression(theta[1]),"","","",expression(theta[2]),"","","",expression(theta[3])))
pp

enter image description here

In this example, the labels should be at 2.5, 6.5 and 8.5.


Solution

  • A different solution:

    library(ggplot2)
    
    pp <- ggplot(mat, aes(x = as.numeric(variable), y = value, 
                          group = variable, fill = variable_grouping)) + 
      geom_violin(scale="width", adjust = 1, width = 0.5) + xlab("variable") +
      scale_x_continuous(breaks = c(2.5, 6.5, 10.5), 
                  labels = c(expression(theta[1]),expression(theta[2]),expression(theta[3])))
    pp
    

    enter image description here