[R] how to plot chi-square distribution in the graph

Greg Snow Greg.Snow at imail.org
Mon Oct 27 17:17:02 CET 2008


Here is an example of adding the distribution curve to a histogram:

x <- rchisq(100, 5)
hist(x, prob=TRUE)
curve( dchisq(x, df=5), col='green', add=TRUE)
curve( dchisq(x, df=10), col='red', add=TRUE )

It may be easier to compare the therotical curve to a density estimate rather than the histogram:

lines( density(x), col='orange')


Here is one way to dynamically change the df to see how the fit compares:

tmpfun <- function(x,df=1) {
        hist(x, prob=TRUE)
        curve( dchisq(x, df=df), col='blue', add=TRUE )
}

TeachingDemos::tkexamp( tmpfun(x), list( df=list('slider', from=1, to=15)))


Another approach that may give a better feel for the fit is the hanging rootogram:

library(vcd)

tmp <- hist(x, plot=FALSE)
rootogram( tmp$counts, diff(pchisq( tmp$breaks, df=5 )*length(x) ) )
rootogram( tmp$counts, diff(pchisq( tmp$breaks, df=10 )*length(x) ) )

tmpfun2 <- function(x, df=1) {
        tmp <- hist(x, plot=FALSE)
        rootogram( tmp$counts, diff(pchisq(tmp$breaks, df=df)*length(x) ) )
}

TeachingDemos::tkexamp( tmpfun2(x), list( df=list('slider', from=1, to=15)))


Hope this helps,

--
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of leo_wa
> Sent: Friday, October 24, 2008 9:22 PM
> To: r-help at r-project.org
> Subject: [R] how to plot chi-square distribution in the graph
>
>
> if i want to plot the chi-square distribution with a different degree
> of
> freedom how can i plot it in the graph?Sometimes i plot the histogram
> and
> cut it in a lot of piece.It's distribution like a chi-square.So i want
> to
> plot the chi-square with a different degree of freedom to compare it .
> --
> View this message in context: http://www.nabble.com/how-to-plot-chi-
> square-distribution-in-the-graph-tp20160946p20160946.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list