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

时间:2016-07-26 11:42:41

标签: r density-plot

根据此website的示例,我们可以为data.frame

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

我的问题非常简单,如何为每个因子添加一条垂直线,代表中位数意味着

1 个答案:

答案 0 :(得分:2)

这是卑鄙的示例。要计算中位数,只需在聚合函数中将“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)

Desired Plot