Search code examples
rggplot2violin-plotgeom-segment

Decrease space from y-axis after adding geom_segments to geom_violin plot


I have been trying to plot some data with geom_violin and add two geom_segments on each side of the plot. I would like to reduce the space between the violins and the y-axis, which increases when I add a geom_segment. Moreover, I would like to increase the space between violins in Condition 1 and Condition 2.

Any suggestion? Below you find a reproducible example.

 classes = c('A','B','C')

meanCond1 = 0
meanCond2 = 2
n_size = 50

finalRes1 = NULL

for(id in classes){
   tmp_df = rnorm(n = n_size,mean = meanCond1, sd = 1)
   tmp_res = data.frame(type = 'Condition1', value = tmp_df,model = id)
   finalRes1 = rbind(finalRes1,tmp_res)
}

finalRes2 = NULL

for(id in classes){
   tmp_df = rnorm(n = n_size,mean = meanCond2, sd = 1)
   tmp_res = data.frame(type = 'Condition2', value = tmp_df,model = id)
   finalRes2 = rbind(finalRes2,tmp_res)
}

finalTot = rbind(finalRes1,finalRes2)
finalTot$type = as.factor(finalTot$type)

plotWithoutSegment = ggplot(finalTot, aes(x = type, y = value, fill = model)) +
  geom_violin(draw_quantiles = c(0.05, 0.95))+
  scale_x_discrete(expand = c(0,0))+
  ylab('')+xlab('')+
  theme_bw()

enter image description here

plotWithSegment = ggplot(finalTot, aes(x = type, y = value, fill = model)) +
  geom_violin(draw_quantiles = c(0.05, 0.95))+
  geom_segment(aes(x = 0, y = 1.5, xend = 1.5, yend = 1.5),color = '#023047',linetype = 'dashed', linewidth = 1)+
  geom_segment(aes(x = 3, y = 2.5, xend = 1.5, yend = 2.5),color = '#023047',linetype = 'dashed', linewidth = 1)+
  scale_x_discrete(expand = c(0,0))+
  ylab('')+xlab('')+
  theme_bw()

enter image description here


Solution

  • To get rid of the white space you have to set the right start and end positions for the segments, i.e. your discrete x scale starts at .5 (not 0) and ends at 2.5 (not 3). And to add some more space between the groups of violins you could reduce the width=:

    Note: I switched to annotate to add both segments. But of course does this also work with geom_segment.

    library(ggplot2)
    
    set.seed(123)
    
    ggplot(finalTot, aes(x = type, y = value, fill = model)) +
      geom_violin(
        draw_quantiles = c(0.05, 0.95),
        width = .6
      ) +
      annotate(
        geom = "segment",
        x = c(1, 2) - .5,
        y = c(1.5, 2.5),
        xend = c(1, 2) + .5,
        yend = c(1.5, 2.5),
        color = "#023047",
        linetype = "dashed",
        linewidth = 1
      ) +
      scale_x_discrete(expand = c(0, 0)) +
      ylab("") +
      xlab("") +
      theme_bw()
    

    enter image description here