Skip to content
Prev 5810 / 398506 Next

Followup: Re: [R] Interaction Plots in R

Well, I've been using that function a lot lately and so I've improved it
considerably, up to the point of being useful. Having a bit of a bad
conscience for my last version (it was rather ugly), I'd like to post a
better one. It uses colours, draws a legend (which can be reordered) and
does a better job with axis labels. What's more, I've since discovered the
"matlines" function :-) .

If anyone else needs interaction plots similar to S-Plus, here you go:

----------------------------------------------------------
interaction.plot<-
function (f1, f2, data, main = "Interaction Plot",
    xlab = deparse(substitute(f2)),
    ylab = paste("Mean of", deparse(substitute(data))),
    legend=T, leg.order = 1:n1, ...)
{

    # f1,f2: factors. data: data vector
    # (extraction from matrix or data.frame not implemented)
    
    cellmeans <- tapply(data, list(f1, f2), mean)
    n1 <- nlevels(f1)
    n2 <- nlevels(f2)
    xr <- c(1, n2)
    yr <- range(cellmeans)
    plot(0, 0, type = "n", xaxt = "n", xlim = xr, ylim = yr,
        main = main, xlab = xlab, ylab = ylab)
    matlines(t(cellmeans), lty = 1, col = 1:n1)
    axis(1, at = 1:n2, labels = as.character(levels(f2)))
    if(legend)    
        legend(locator(1), legend = rownames(cellmeans)[leg.order],
            lty = 1, col = (1:n1)[leg.order])

    # locator(1) waits for user to choose legend location
    # (click marks upper left corner)
    # legend entries get ordered according to leg.order

    invisible(list(cellmeans = cellmeans))
    # cellmeans are returned
}
--------------------------------------------------------

 -- 
Kaspar Pflugshaupt
Geobotanisches Institut ETH Zurich
mailto: pflugshaupt at geobot.umnw.ethz.ch