Get startedGet started for free

Violins with boxplots

If we still want the handy summary statistics that a boxplot provides while not sacrificing the benefits of a violin plot, we can simply add a geom_boxplot() on top of the violin geometry in our plot object.

One issue we run into when doing this, however, is that the boxplots are awkwardly wide. We only need to see where the horizontal lines are and not much more. Luckily, geom_boxplot() has the argument width, which scales the width of the boxplot (e.g. 0.5 = half-width).

Modify the plot we just made to have a boxplot between the violin and point geometries. In addition, change the points to have shape = 95 which is a horizontal tick mark. Lastly, we forgot to tell the user our kernel width, let's do that now.

This exercise is part of the course

Visualization Best Practices in R

View Course

Exercise instructions

  • Add a geom_boxplot() between violin and point geometries.
  • Set box alpha to 0 and width to 0.3.
  • Change point geometry to shape = 95 and delete size argument.
  • Give plot a subtitle with labs(subtitle = 'Gaussian kernel SD = 2.5').

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

md_speeding %>% 
    filter(vehicle_color == 'RED') %>%
    ggplot(aes(x = gender, y = speed)) + 
    geom_violin(bw = 2.5) +
    # add a transparent boxplot and shrink its width to 0.3
    ___ +
    # Reset point size to default and set point shape to 95
    geom_point(alpha = 0.3, size = 0.5) +
    # Supply a subtitle detailing the kernel width
    ___
Edit and Run Code