add vertical line of the mean to density plot

前提是你 提交于 2019-12-19 04:58:11

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/38588976/add-vertical-line-of-the-mean-to-density-plot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!