Reputation: 277
I'm trying to make a simple graph for binomial distribution in R.
So the question is "There are 20 patients, and what is the probability of operating on 4 patients successfully, (given that the probability = 0.8)."
What I did is
x <- rbinom(4, size= 20, prob = 0.8)
y <- pbinom(x, size = 20, prob = 0.8)
plot(y, type="l")
But I'm not sure if this is the right way of graphing it..
Upvotes: 2
Views: 7026
Reputation: 118799
In general, your question for visualisation comes when your question is something like:
What's the probability of having "at least" 16 successes out of 20 operations given that the probability of success is 0.8?
This can be done by using the binomial formula which is:
p(x=k) = choose(n, k) * .8^k * .2^(n-k) # equivalent to dbinom(k, n, prob=0.8)
We need the same for k = 16..20
and sum up all these values to get the probability of sucess in at least 16 out of 20. This is done using dbinom
as:
sum(dbinom(16:20, 20, prob=0.8)) # 0.6296483
Note that the probability of at least 4 successes at this success rate(0.8) would be just 1. That is, we most definitely will have at least 4 successes. That's why I chose relatively high amount of successes.
To plot this (using ggplot2
):
library(ggplot2)
df <- data.frame(x=1:20, prob=dbinom(1:20, 20, prob=0.8))
ggplot(df, aes(x = x, y = prob)) +
geom_line() +
geom_ribbon(data = subset(df, x >= 16 & x <= 20),
aes(ymax = prob),
ymin = 0,
fill = "red",
colour = NA,
alpha = 0.5)
This gives you something like:
Hope this helps.
Upvotes: 8