Function that will add elements to an existing plot via different draw functions per each level of a grouping factor.

draw_by_group(dtf, variable, groups, draw_fun, ...)

Arguments

dtf

A data frame.

variable

A character string, the column with the grouping levels.

groups

The grouping levels to plot over.

draw_fun

A function, either draw_dots, draw_lines, or draw_boxplots.

...

Additional arguments for the relevant function. For a given argument, a list with different values per group can be provided.

Value

Adds elements to an existing plot per each group level.

Examples

# Compute mean, SE, and 95% CI limits for data set
dtf <- aggregate(
  mtcars$mpg, list( mtcars$cyl ), function(x) c( mean(x), sem(x) )
)
dtf$X <- 1:3
dtf$M <- dtf$x[,1];
dtf$LB <- dtf$x[,1] - dtf$x[,2] * 1.96
dtf$UB <- dtf$x[,1] + dtf$x[,2] * 1.96

# 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 means and error bars by car cylinder type
draw_by_group(
  dtf, variable = 'Group.1', groups = c( 4, 6, 8 ),
  draw_fun = draw_dots,
  columns = c( 'X', 'M', 'LB', 'UB' ),
  bg = list( 'black', 'blue', 'red' ),
  pch = list( 21, 22, 24 )
)

# 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 )