user 31466
user 31466

Reputation: 699

R, graph of binomial distribution

I have to write own function to draw the density function of binomial distribution and hence draw appropriate graph when n = 20 and p = 0.1,0.2,...,0.9. Also i need to comments on the graphs.

I tried this ;

   graph <- function(n,p){
               x <- dbinom(0:n,size=n,prob=p)
               return(barplot(x,names.arg=0:n))
            }


   graph(20,0.1)
   graph(20,0.2)
   graph(20,0.3)
   graph(20,0.4)
   graph(20,0.5)
   graph(20,0.6)
   graph(20,0.7)
   graph(20,0.8)
   graph(20,0.9)

   #OR
   graph(20,scan())

My first question : is there any way so that i don't need to write down the line graph(20,p) several times except using scan()?

My second question :

I want to see the graph in one device or want to hit ENTER to see the next graph. I wrote

   par(mfcol=c(2,5))
   graph(20,0.1)
   graph(20,0.2)
   graph(20,0.3)
   graph(20,0.4)
   graph(20,0.5)
   graph(20,0.6)
   graph(20,0.7)
   graph(20,0.8)
   graph(20,0.9)

but the graph is too tiny. How can i present the graphs nicely with giving head line n=20 and p=the value which i used to draw the graph?[though it can be done by writing mtext() after calling the function graphbut doing so i have to write a similar line few times. So i want to do this including in function graph. ]

My last question :

About comment. The graphs are showing that as the probability of success ,p is increasing the graph is tending to right, that is , the graph is right skewed.

Is there any way to comment on the graph using program?

Upvotes: 9

Views: 23600

Answers (2)

Hong Ooi
Hong Ooi

Reputation: 57686

Plotting base graphics is one of the times you often want to use a for loop. The reason is because most of the plotting functions return an object invisibly, but you're not interested in these; all you want is the side-effect of plotting. A loop ignores the returned obects, whereas the *apply family will waste effort collecting and returning them.

par(mfrow=c(2, 5))
for(p in seq(0.1, 1, len=10))
{
    x <- dbinom(0:20, size=20, p=p)
    barplot(x, names.arg=0:20, space=0)
}

Upvotes: 2

agstudy
agstudy

Reputation: 121578

Here a job of mapply since you loop over 2 variables.

graph <- function(n,p){
  x <- dbinom(0:n,size=n,prob=p)
  barplot(x,names.arg=0:n,
         main=sprintf(paste('bin. dist. ',n,p,sep=':')))
}
par(mfcol=c(2,5))
  mapply(graph,20,seq(0.1,1,0.1))

enter image description here

Upvotes: 8

Related Questions