【发布时间】:2015-05-24 18:56:11
【问题描述】:
这个论坛已经为我生成代码提供了很多帮助,我希望它返回一个特定变量的直方图,上面覆盖着它的经验正态曲线。我使用 ggplot2 和 stat_function 编写代码。 不幸的是,该代码生成了具有正确直方图的图,但正态曲线是零处的直线(以下代码生成的图中的红线)。
对于这个最小的示例,我使用了 mtcars 数据集 - 在我的原始数据集上观察到了 ggplot 和 stat_function 的相同行为。
这是编写和使用的代码:
library(ggplot2)
mtcars
hist_staff <- ggplot(mtcars, aes(x = mtcars$mpg)) +
geom_histogram(binwidth = 2, colour = "black", aes(fill = ..count..)) +
scale_fill_gradient("Count", low = "#DCDCDC", high = "#7C7C7C") +
stat_function(fun = dnorm, colour = "red")
print(hist_staff)
我也尝试指定 dnorm:
stat_function(fun = dnorm(mtcars$mpg, mean = mean(mtcars$mpg), sd = sd(mtcars$mpg))
这也没有解决 - 返回一条错误消息,指出参数不是数字。
我希望你们能帮助我!提前非常感谢!
最好的,詹尼克
【问题讨论】:
-
stat_function(fun = dnorm, arg = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg))) -
stat_function(fun = dnorm, args = list(mean = mean(mtcars$mpg), sd = sd(mtcars$mpg)))
-
@ManojKumar (a) cmets 属于,嗯,Comments 和 (b) 在决定对工作代码进行上述评论之前查找“r 函数参数部分匹配”。
-
此链接提供了更好的解决方案。 stackoverflow.com/questions/5688082/…