R:line函数未生成行

时间:2018-09-19 07:37:13

标签: r plot histogram

我正在尝试在直方图中添加密度曲线。

这是我的代码:

    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

我的直方图正确,但密度曲线不正确。请问有人可以帮我吗?预先谢谢你!

1 个答案:

答案 0 :(得分:1)

问题很可能是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"