Violin Plot with Plotly
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
ph <- ggplot(mtcars, aes(x = mpg, y = factor(cyl))) + geom_violin(fill = NA, draw_quantiles = c(0.25, 0.5, 0.75)) ph
We easily create the interactive plotly chart by
Not only that, the quantile lines disappeared too, which was reported back in 2018.
The workaround is to use
ggplotly(pv + coord_flip())
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
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.