equanimity
equanimity

Reputation: 2533

Nested for loop to generate side-by-side plots

I would like to be able to generate normal probability (QQ) plots of:

a) the chi-square distribution

b) the t-distribution

I'd like to display these plots side-by-side (e.g. plot of chi-square on the left and plot of t-distribution on the right).

I'm using a different number of degrees of freedom for each distribution. Here is my code:

n = 100

par(mfrow = c(2,2))

for (i in seq(from=1, to=100, by=10)) {
  x <- rchisq(n, i)
  qqnorm(x, main = paste('Q-Q Plot ~ chi-square dist | df =', i))
}



for (j in seq(from=1, to=30, by=3)){
  y <- rt(n, j)
  qqnorm(y, main = paste('Q-Q Plot ~ t-dist | df =', j))
}

This works, but it builds the plots such that the t-distribution is beneath the chi-square plots. I'd like the plots to be displayed side-by-side as the number of degrees of freedom increases. For example:

chi-square (df=1)      t-dist (df=1)
chi-square (df=11)     t-dist (df=4)
chi-square (df=21)     t-dist (df=7)
...                    ...
chi-square (df=91)     t-dist (df=28)

I tried a nested for loop, but couldn't get it to work. Any assistance would be most appreciated.

Thanks!

Upvotes: 1

Views: 107

Answers (1)

jpsmith
jpsmith

Reputation: 17185

You could try something like this to put the figures in the same loop:

par(mar=c(1,1,1,1))
par(mfrow = c(10,2))
dfs <- cbind(seq(from=1, to=100, by=10), seq(from=1, to=30, by=3))
for (i in 1:nrow(dfs)) {
  x <- rchisq(n, dfs[i,1])
  y <- rt(n, dfs[i,2])
  qqnorm(x, main = paste('Q-Q Plot ~ chi-square dist | df =', dfs[i,2]))
  qqnorm(y, main = paste('Q-Q Plot ~ t-dist | df =', dfs[i,1]))
}

enter image description here

Upvotes: 1

Related Questions