我想在我的直方图中添加密度曲线。
这是我的代码:
privateCollege <- data.frame(filter(college.df, Private == "Yes"))
publicCollege <- data.frame(filter(college.df, Private == "No"))
hist(privateCollege$PhD, main = "PhD holder in Private Colleges")
hist(publicCollege$PhD, main = "PhD holder in Public Colleges")
line(density(privateCollege$PhD, adjust = 2))
我期待我的代码的最后一行给我直方图“私立大学的博士学位”的密度曲线,但这是我得到的:
Call:
line(density(privateCollege$PhD, adjust = 2))
Coefficients:
[1] 9.124e-04 5.808e-05
我的直方图是正确的而不是密度曲线。有人可以帮帮我吗?先感谢您!
问题很可能是R默认情况下绘制计数/频率直方图,请参阅https://stats.stackexchange.com/questions/169061/why-is-my-density-plot-just-a-line-on-the-bottom,因此您需要在freq=FALSE
调用中设置hist
,即:
privateCollege <- data.frame(filter(college.df, Private == "Yes"))
publicCollege <- data.frame(filter(college.df, Private == "No"))
hist(privateCollege$PhD, main = "PhD holder in Private Colleges", freq=FALSE)
hist(publicCollege$PhD, main = "PhD holder in Public Colleges", freq=FALSE)
lines(density(privateCollege$PhD, adjust = 2))
另见https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/hist.html
编辑:除了需要设置freq=FALSE
,你的代码中也有一个拼写错误,你需要使用函数lines
,理想情况下选项type="l"