-1

How can I plot a chi-square density graph in R?

I got the following codes but I'm not sure how to manipulate them:

curve( dchisq(x, df=28), col='red', main = "Chi-Square Density Graph",
          from=0,to=60)
xvec <- seq(7.5,60,length=101)
pvec <- dchisq(xvec,df=28)
polygon(c(xvec,rev(xvec)),c(pvec,rep(0,length(pvec))),
        col=adjustcolor("black",alpha=0.3))

Could someone explain what the codes mean?

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
Yann Chan
  • 1
  • 1
  • 1
  • 2
    Manipulate it how? The code you posted plots a chi-square distribution. – emilliman5 Feb 21 '18 at 14:30
  • Welcome to StackOverflow. In order to ask a better question please read [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) and [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Rui Barradas Feb 21 '18 at 14:33

1 Answers1

3

The package ggplot2 provides an easy way to plot Chi square distributions. You have to simply specify a stat_function with dchisq as your function and then a list to args that indicates the degrees of freedom.

For example, here is sample code for a Chi square distribution for 4 degrees of freedom:

library(ggplot2)

ggplot(data.frame(x = c(0, 20)), aes(x = x)) +
     stat_function(fun = dchisq, args = list(df = 4))
Peter Miksza
  • 347
  • 3
  • 11