首页 文章

使用ggplot2叠加不对称t分布

提问于
浏览
2

我试图表明非对称t分布或正态分布是否更适合某个数据集 . 在这样做时,我决定叠加拟合的正态分布和拟合的t分布 . 对于正态分布,使用stat_fun没问题:

x <- data.frame(rnorm(500))
    names(x) <- c("test.data")

    ggplot(x,aes(x=test.data))  +  
      stat_function(fun = dnorm, args=list(mean=mean(x$test.data,na.rm=TRUE),
      sd=sd(x$test.data,na.rm=TRUE)), aes(colour = 'Normal')) +
      geom_histogram(aes(y = ..density..), alpha = 0.4)

产生下图:

enter image description here

现在我想对非对称t分布做同样的事情,其中我有形状(nu),位置(mu),色散(sigma)和非中心性参数(gamma) . 如果我在stat_function函数中输入t分布,我只能使用包统计信息中的dt函数指定shape和non-centrality参数 .

有没有办法在我的直方图上叠加t分布,我可以预先指定所有四个参数?

1 回答

  • 3

    试试这个:

    library(ggplot2)
    set.seed(1)
    x <- data.frame(rt(5000,df=5,ncp=1)*10+7)
    names(x) <- c("test.data")
    
    # Define a Student t distribution with shape (nu) and location (mu)
    dt2 <- function(x, mu, nu, df, ncp) {
      dt((x-mu)/nu,df,ncp)/nu
    }
    
    ggplot(x,aes(x=test.data))  +  
    stat_function(fun = dt2, args=list(mu=7, nu=10, df=5, ncp=1), 
                  aes(colour = 'Student t'), lwd=1) +
    geom_histogram(aes(y = ..density..), bins=100, alpha = 0.4)
    

    enter image description here

相关问题