将平均值的垂直线添加到密度图

add vertical line of the mean to density plot

按照此 website 中的示例,我们可以为 data.frame

中的多个因素生成密度图
library(sm)
attach(mtcars)
sm.density.compare(mpg, cyl, xlab="Miles Per Gallon")

我的问题很简单,如何为代表中位数均值的每个因子添加一条垂直线?

这是 均值 的示例。要计算 中位数 ,只需在聚合函数中将 "FUN = mean" 替换为 "FUN = median"。

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)