Friday, August 05, 2005

Combination plot: bar + line plot with their respective y-axis on opposite sides

Mariëtte wanted a combined plot of the two tables ('RT' and 'errors') below. Specifically, she asked for
  • - a plot with two y-axes
  • - the y-axis on the right should be for the 'errors' table (it should be smaller)
  • - the y-axis on the left should be for the RTs (Reaction Times) table (it should be larger)
  • - the Errors should be plotted as bars
  • - the RTs should be plotted as lines
  • - on the x-axis, the tick marks correspond to the different age groups, and labelled accordingly


  • X: age                                        
       RT (ms)         (Y-axis on the left, lines plot)
            repetition      alternation
    7-yrs  814     967
    11-yrs  500     574
    15-yrs  424     472
    21-yrs  394     446

       errors (%)      (Y-axis on the right, bar plot)
            repetition      alternation
    7-yrs  10      13
    11-yrs  6       7
    15-yrs  6       6
    21-yrs  4       3

    A possible solution is to plot the Error table with barplot, and to rescale the RT table to the same range as Error, and draw the RT axis by hand (i.e. specify the appropriate labels by hand):

    # first get the data
    RT = matrix(c(814, 500, 424, 394, 967, 574, 472, 446),4,2)
    colnames(RT) = c('repetition','alternation')
    rownames(RT) = c('7-yrs','11-yrs','15-yrs','21-yrs')

    # another way is to select the table above,
    # press Ctrl-C, and run the command
    error <- read.table(file='clipboard')

    opar = par(mar=c(5,4,4,5))
    ratio = 2;       # parameter to vary the height
                     # ratio of error and RT axes
    extray = 0.1;    # parameter to increas the y-axis range
    a = barplot(t(as.matrix(error)), beside=TRUE,
                axes=FALSE, xlim=c(0,13), ylim =
                c(0,(ratio+extray)*max(error)),
                ylab='')
    x = apply(a,2,mean)
    matplot(x, RT * ratio * max(error)/max(RT),
            axes=FALSE, type='b', pch=1:2, add=TRUE)
    axis(4, las=2)
    mtext('error (%)',4,line=3)
    rtas = pretty(c(0,range(RT)))
    axis(2, at=rtas*ratio*max(error)/max(RT), rtas, las=2)
    mtext('RT',2,line=3)
    par(opar)

    The result:

    Combined bars and lines plot (Data were provided by Mariƫtte Huizinga

    0 Comments:

    Post a Comment

    << Home