I would like to generated a mix of five Gamma's distribution where r=3, lambda_i=1/i and theta_i= i/15 while i is in {1, 2 , 3, 4, 5}. Later I would like to plot them to show the results.
I performed some code to generate one variable,
n=5000
k=sample(1:5,size=n,replace=TRUE,prob=(1:5)/15)
rate=1/k
x=rgamma(n,shape=3,rate=rate)
But I have no idea what to do next. Should I make a vector containing five variables like this one and plot it?
CodePudding user response:
Here is the missing fragment which you need to plot mixes distribution:
plot(density(x),xlim=c(0,40),ylim=c(0,.3),lwd=3,xlab='x',main='')
for (i in 1:5)
lines(density(rgamma(n,3,1/i)),col=i 1,lwd=3)
CodePudding user response:
Here is another way of generating the plot using ggplot2 as you mentioned. A density plot of the five Gamma distributions can be created using ggplot2 in the manner shown here. A density plot of the five Gamma distributions will be produced by this, with each distribution being coloured differently based on the value of k.
x = rep(NA,n)
for(i in 1:5){
x[k==i] = rgamma(sum(k==i),shape=3,rate=rate[i])
}
library(ggplot2)
data = data.frame(x = c(x, rgamma(n, 3, 1/2), rgamma(n, 3, 1/3), rgamma(n, 3, 1/4), rgamma(n, 3, 1/5)),
k = c(rep(1, n), rep(2, n), rep(3, n), rep(4, n), rep(5, n)))
ggplot(data, aes(x = x, fill = factor(k)))
geom_density(alpha = 0.5)
scale_fill_manual(values = 1:5)
xlim(c(0, 40))
ylim(c(0, 0.3))
xlab('x')
ggtitle('')