【问题标题】:Can't fit a normal curve to a grouped histogram无法将正态曲线拟合到分组直方图
【发布时间】:2016-03-30 18:05:47
【问题描述】:

我正在为分配给我的任务而苦苦挣扎。 我们必须制作一个叠加了正常拟合的分组直方图。 现在,我已经设法在 Basic R graph、Lattice 和 Ggplot 中获得了分组直方图。在 Basic R graph 中,我也能得到一条正态曲线,但在 Lattice 和 Ggplot 中,我似乎没有这样做。

这是我来自 Lattice 和 Ggplot 的 R 脚本:

#Lattice:
library(lattice)
histogram(~SBP, data= DataSBP, breaks=10,
          type=c("density"), 
          groups = User, panel = function(...)panel.superpose(...,panel.groups=panel.histogram, col=c("navy","maroon3"),alpha=0.4),
          auto.key=list(columns=2,rectangles=FALSE, col=c("navy","maroon3")))
panel.mathdensity(dmath=dnorm, col="black", args=list(mean=mean(x, na.rm = TRUE), sd=sd(x, na.rm = TRUE)))

当我尝试命令“panel.mathdensity”时没有任何反应。

# Ggplot
library(ggplot2)
ggplot(DataSBP, aes(x=SBP)) + geom_histogram(aes(y=..density.., x=SBP, colour=User, fill=User),alpha=0.5, binwidth = 5, position="identity")
+ stat_function(fun = dnorm, args = list(mean = SBP.mean, sd = SBP.sd))

如果我尝试 stat_function 命令,我总是得到错误“SBP.mean”找不到,这可能意味着我必须定义 SBP.mean,但是如何?

我的数据是这样的:

User SBP    
No 102    
No 116    
No 106    
...    
Yes 117    
Yes 127    
Yes 111    
...

我的图表如下所示:

【问题讨论】:

    标签: r histogram


    【解决方案1】:

    您是否正在寻找类似的东西?我无权访问您的数据集,所以我使用了 iris 数据集

    library(dplyr); library(ggplot2)
    
    meanSe <- iris %>% 
      filter(Species == "setosa") %>% 
      summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
    #
    meanVe <- iris %>% 
      filter(Species == "versicolor") %>% 
      summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
    #
    meanVi <- iris %>% 
      filter(Species == "virginica") %>% 
      summarise(means = mean(Sepal.Length), sd=sd(Sepal.Length))
    #
    ggplot(iris, aes(x=Sepal.Length, color=Species, fill=Species)) +
      geom_histogram(aes(y=..density..), position="identity", binwidth=.5) + 
      stat_function(fun = dnorm, color="red", args=list(mean=meanSe$means, sd=meanSe$sd)) + 
      stat_function(fun = dnorm, color="green", args=list(mean=meanVe$means, sd=meanVe$sd)) + 
      stat_function(fun = dnorm, color="blue", args=list(mean=meanVi$means, sd=meanVi$sd)) + 
      theme_bw()
    

    给这个

    【讨论】:

    • 谢谢!我找了好几天才找到!现在我只需要为格子图找到正确的代码:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 2019-11-24
    • 2020-06-10
    相关资源
    最近更新 更多