用R中的ggplot绘制密度曲线的平均值

时间:2017-03-10 20:44:16

标签: r plot ggplot2 density-plot

我需要绘制一条垂直线,每条密度曲线的平均值。

我首先尝试了这个,但是它绘制了整个列的平均值,而不是因子cyl的每个值的平均值。

ggplot(mtcars, aes(mpg, fill = factor(cyl))) 
+ geom_density(alpha = 0.3) 
+ geom_vline(aes(xintercept=mean(mpg),col=factor(cyl)))

enter image description here

我设法通过首先使用data.table计算方法来绘制3个独立的方法。

mtcars <- data.table(mtcars)
mtcars[,mpg_mean_by_cyl:=mean(mpg),by=cyl]

ggplot(mtcars, aes(mpg, fill = factor(cyl))) + geom_density(alpha = 0.3)+
geom_vline(aes(xintercept=mpg_mean_by_cyl,col=factor(cyl)))

enter image description here

我的问题是:有没有办法直接用ggplot来做?密度曲线对于每个圆柱值都是很好的分离,为什么垂直线没有发生?

0 个答案:

没有答案