Overlay a t-distribution to my histogram using R?

最后都变了- 提交于 2019-12-12 00:34:46

问题


How can I overlay a t-density to my histogram using R? Here's my function:

simfun <- function(a=56.25102409,b=1.78977412,c=0.08664925,n=18,x1.sd=18.87671,x2.sd=18.87671,e.sd=18.87671) {
   X1 <- rnorm(n, mean=0, sd=x1.sd)
   X2 <- rnorm(n, mean=0, sd=x2.sd) 
   e <-  rnorm(n, mean=0, sd=e.sd)
   Z <- a+b*X1+c*X2+e 
   data.frame(X1,X2,Z)
}

statfun <- function(samples) {
    coef(lm(Z~X1+X2,data=samples))
}

library(plyr)
B=raply(1000,statfun(simfun()))

(hist(B[,2]))

回答1:


Change the last line to:

hist(B[,2], prob=TRUE)

to get the scaling correct, then do

curve( dt(x, df=15), add=TRUE, col='blue' )

changing the df and color to whatever values you want.




回答2:


As November 2019 the way I found to get this plot is with a new plot. Apparently, using dt with curve assumes the x is normalized. The df parameter could be estimated with fitdistr from MASS package.

fit.t.tc <- fitdistr(B[,2], "t", hessian = TRUE)
(param.t=fit.t.tc$estimate)

dh=hist(B[,2], prob=TRUE)
#to get the scaling correct, then do
curve( dt(x, df=param.t["df"]), add=TRUE, col='blue' ) # ??
par(new = TRUE)
ss=seq(range(dh$mids)[1],range(dh$mids)[2],length.out = 1000)
x=((ss-param.t["m"])/param.t["s"])
plot(x,100*dt(x=x,df=param.t["df"]), type="l",
      col="red", lwd=3,xlab="",axes=F,ylab="")



来源:https://stackoverflow.com/questions/19103582/overlay-a-t-distribution-to-my-histogram-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!