I would like to draw some violin plots with ggplot2, but I noticed that median and first and third quartile are not automatically displayed. I believe these plots would be m
geom_violin
has an argument draw_quantiles
that allows you to specify which quantiles to include. Here is an example of 1st, 2nd, and 3rd quartiles on iris.
require(ggplot2)
ggplot(iris, aes(Species, Sepal.Length)) +
geom_violin(draw_quantiles = c(0.25, 0.5, 0.75))
One way to do this is to just put a thin box plot over the top of it. Here's an example with the iris data:
require(ggplot2)
ggplot(iris,aes(Species,Sepal.Length))+geom_violin()+geom_boxplot(width=.1)
I discovered this from a google search:
First, this Stack Overflow post indicates that you can add stat_summary(fun.y="median", geom="point")
to plot the median on a violin plot as a point.
With regard to quartiles, you will likely have to write your own function for the fun.y argument above, as demonstrated on here. E.g.:
median.quartile <- function(x){
out <- quantile(x, probs = c(0.25,0.5,0.75))
names(out) <- c("ymin","y","ymax")
return(out)
}
The full code might look like this:
require(ggplot2)
median.quartile <- function(x){
out <- quantile(x, probs = c(0.25,0.5,0.75))
names(out) <- c("ymin","y","ymax")
return(out)
}
ggplot(iris,aes(Species,Sepal.Length))+
geom_violin()+
stat_summary(fun.y=median.quartile,geom='point')