I tried to model this question in order to have a portion of a curve shaded between two values. My code is:
n_samples <- 1e4
p_grid <- seq( from=0 , to=1 , length.out=1000 )
prior <- rep( 1 , 1000 )
likelihood <- dbinom( 6 , size=9 , prob=p_grid )
posterior <- likelihood * prior
posterior <- posterior / sum(posterior)
samples <- sample( p_grid , prob=posterior , size=n_samples , replace=TRUE )
x1 <- 0.5
x2 <- 0.7
dens <- density(samples)
plot(dens)
with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="gray"))
However, I get the error:
Error in xy.coords(x, y, setLab = FALSE) : 'x' and 'y' lengths differ
Am a beginner in R and don't know what needs to be fixed. Any help much appreciated!