Function to add a boxplot at a specified x-axis position to an existing figure.

draw_boxplots(
  x,
  y = NULL,
  columns = NULL,
  width = 0.25,
  lwd = 2,
  col = "black",
  bg = NA
)

Arguments

x

Either a single value or a data frame.

y

An optional vector of 5 values giving the cut-offs for the boxplot (typically the 2.5%, 25%, 50%, 75%, and 97.5% quantiles).

columns

A character vector, giving the column with the x-axis value and the 5 columns with the cut-offs for the boxplot, respectively.

width

The spacing to add to the left and right of the x-axis value.

lwd

The width of the lines (see par).

col

The fill color for the box component.

Value

Adds a boxplot to an existing figure.

Examples

# Compare normal and log-normal distributions
dtf_data <- data.frame(
  Normal = rnorm( 100, 100, sqrt( 225 ) ),
  Log_normal = exp(
    rnorm( 100, 4.594045, sqrt( 0.02225061 ) )
  )
)

# Create blank plot
xl <- c( .5, 2.5 )
yl <- c( 50, 150 )
plot_blank( xl, yl )

# Add boxplots

y <- quantile( dtf_data$Normal, prob = c( .025, .25, .5, .75, .975 ) )
draw_boxplots( 1, y )

y <- quantile( dtf_data$Log_normal, prob = c( .025, .25, .5, .75, .975 ) )
draw_boxplots( 2, y, col = 'blue' )


# Compute cut-offs for boxplots for data set
dtf <- aggregate(
  mtcars$mpg, list( mtcars$cyl ),
  quantile, prob = c( .025, .25, .5, .75, .975 )
)
dtf$X <- 1:3
colnames( dtf$x ) <- 'Q' %p% c( '02.5', '25.0', '50.0', '75.0', '97.5' )
dtf <- cbind( dtf[,c('Group.1', 'X') ], dtf$x )

# Create blank plot
xl <- c( .5, 3.5 )
yl <- c( 5, 35 )
plot_blank( xl, yl )
draw_hv( h = yl, l = xl )
draw_hv( v = xl, l = yl )

# Add boxplots per cylinder type
draw_boxplots(
  dtf[1,], bg = palettes( index = 1 )
)
draw_boxplots(
  dtf[2,], bg = palettes( index = 2 )
)
draw_boxplots(
  dtf[3,], bg = palettes( index = 3 )
)

# Add axes and labels
draw_axes( 1:3, dtf$Group.1 )
mtext( 'Cylinders', side = 1, line = 2, cex = 1.25 )
draw_axes( c( 10, 20, 30 ), side = 2 )
mtext( 'MPG', side = 2, line = 2, cex = 1.25 )