
Last chance! 50% off unlimited learning
Sale ends in
Adds a shaded interval to an existing density plot or regression plot.
shade( object , lim , label=NULL , col="#00000066" , border=NA , ... )
A density
or formula
object that defines the density OR a matrix
object that defines the plot region. See details.
For a density, a vector of two values, indicating upper and lower bounds of interval, on the horizontal axis. For a plot region, a list of x-axis values corresponding to y-axis points in the matrix object.
Optional label to center in interval.
Color to shade the interval. Default is transparent gray.
Border of shaded region. Default is no border, NA
.
Other parameters to pass to polygon
, which actually draws the shaded region.
This function uses polygon
to draw a shaded region under a density curve or on a regression plot. The function assumes the plot already exists. See the examples below.
There are two plotting interfaces, for densities. First, if the density is plotted from kernal estimation, using perhaps density
, then the same density estimate should be passed as the first parameter. See example. Second, if the density is plotted from a series of x and y values, from perhaps a grid approximation, then a formula can be passed to define the curve. See example.
For plotting confidence regions on a regression plot, the matrix object should contain y-axis values defining the border of the region. The first row of the matrix should be the bottom of the region, and the second row should be the top. Each column should correspond to the x-axis values in lim
. See example.
McElreath 2011, Statistical Rethinking.
# NOT RUN {
models <- seq( from=0 , to=1 , length.out=100 )
prior <- rep( 1 , 100 )
likelihood <- dbinom( 6 , size=9 , prob=models )
posterior <- likelihood * prior
posterior <- posterior / sum(posterior)
# using formula interface
plot( posterior ~ models , type="l" )
shade( posterior ~ models , c(0,0.5) )
# using density interface
samples <- sample( models , size=1e4 , replace=TRUE , prob=posterior )
plot( density(samples) )
shade( density(samples) , PCI(samples) )
# plotting a shaded confidence interval on a regression plot
data(cars)
m <- lm( dist ~ speed , cars )
p <- sample.naive.posterior( m )
x.seq <- seq( from=min(cars$speed)-1 , to=max(cars$speed)+1 , length.out=30 )
mu.ci <- sapply( x.seq , function(x) PCI( p[,1] + p[,2]*x ) )
plot( dist ~ speed , cars )
abline( m )
shade( mu.ci , x.seq )
# now a goody non-linear example
m2 <- lm( dist ~ speed + I(speed^2) + I(speed^3) , cars )
p <- sample.naive.posterior( m2 )
x.seq <- seq( from=min(cars$speed)-1 , to=max(cars$speed)+1 , length.out=30 )
mu <- sapply( x.seq , function(x) mean( p[,1] + p[,2]*x + p[,3]*x^2 + p[,4]*x^3 ) )
mu.ci <- sapply( x.seq , function(x) PCI( p[,1] + p[,2]*x + p[,3]*x^2 + p[,4]*x^3 ) )
plot( dist ~ speed , cars )
lines( x.seq , mu )
shade( mu.ci , x.seq )
# }
Run the code above in your browser using DataLab