Search code examples
rdensity-plot

add vertical line of the mean to density plot


Following the example from this website, we can generate a density plot for several factors within a data.frame

library(sm)
attach(mtcars)
sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")

My question is very simple, how can be add a vertical line for each factor which represents the median or the mean?


Solution

  • This is an example for the mean. To calculate the median, simply replace "FUN = mean" with "FUN = median" in the aggregate function.

    library(sm)
    attach(mtcars)
    sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")
    
    means <- aggregate(mpg ~ cyl, FUN = mean)
    abline(v = means[1,2], col = 2)
    abline(v = means[2,2], col = 3, lty = 2)
    abline(v = means[3,2], col = 4, lty = 3)
    

    Desired Plot