Median and quartile on violin plots in ggplot2

前端 未结 3 586
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 05:48

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

相关标签:
3条回答
  • 2020-12-29 06:15

    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))
    

    0 讨论(0)
  • 2020-12-29 06:18

    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)
    

    enter image description here

    0 讨论(0)
  • 2020-12-29 06:37

    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')
    
    0 讨论(0)
提交回复
热议问题