2017-10-20 69 views
2

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

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函数来指定形状和非中心性参数。

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

回答

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