Violin Plot with Plotly

Violin Plot

Violin Plot is a powerful tool for exploratory data analysis, and I prefer it to boxplot.

In ggplot2, the violin plots can be horizontal or vertical by assign the factors to either x or y axis:

Vertial Violin Plot

pv <- ggplot(mtcars, aes(factor(cyl), mpg)) +
       geom_violin(fill = NA, 
                   draw_quantiles = c(0.25, 0.5, 0.75))
pv

Horizontal

ph <- ggplot(mtcars, aes(x = mpg, y = factor(cyl))) +
       geom_violin(fill = NA, 
                   draw_quantiles = c(0.25, 0.5, 0.75))
ph

Plotly

We easily create the interactive plotly chart by ggplotly:

plotly::ggplotly(pv)

And horizontal

ggplotly(ph)

Huh …
Not only that, the quantile lines disappeared too, which was reported back in 2018.

The workaround is to use coord_flip.

 ggplotly(pv + coord_flip())

The coord_flip was discussed in the plotly official website.

With geom_violin(), the y-axis must always be the continuous variable, and the x-axis the categorical variable. To create horizontal violin graphs, keep the x- and y-variables as is and add coord_flip().

I do not think the paragraph quoted above accurately described the situation. The geom_violin in ggplot2 can take categorical data in either x or y axis. The ggplotly does not render correcly when y is categorical. The coord_flip does the job of flipping, so no big deal. However the quantile lines rendering is a bug that worth fixing.

Yunwei Hu
Yunwei Hu

My research interests include robotics, machine learning, and probabilistic modeling.