# [R] Colors in interaction plots

S Ellison S.Ellison at LGCGroup.com
Fri Jan 18 03:38:37 CET 2013

```>But I don't want to plot random colors.
>...
> That's why I have this vector with length 24 - each one matches one line in the "npk" dataset.
... which is not what interaction.plot, or matplot, needs; it needs one per line on the plot.

>How can I inform to the interaction.plot function the color
>corresponding to the block it will plot?

You need a colour vector the same length as the number of levels you're plotting. One easy way to do that would be to do something like
col=1:nlevels(fac), for example as in
interaction.plot(npk\$N, npk\$block, fit, xlab="N",  ylab="yield",col=1:nlevels(fac))

If you have several levels that correspond to the same level of a third factor, you need to provide a cross-reference of sorts. In your toy example, fac corresponds to three levels of block, so one could specify manually. One way of doing it in code, though, could be to use table to identify levels of fac corresponding to levels of block. That sounds a bit complicated, but let's see:

npk\$fac <- fac #just so it's in the same data frame
fac.by.block <- with(npk, table(fac, block)) #cross-reference fac levels by block
fac.index.by.block.level <- apply(fac.by.block, 2, function(x) which(x>0))
#Assumes that you want the first nonzero table entry and that numerical indices are OK
# you could also use which directly: which(fac.by.block >1, arr.ind=TRUE)[,1] gives the same result IF there's a 1:1 fac:block matching

Then
interaction.plot(npk\$N, npk\$block, fit, xlab="N",  ylab="yield",col=(1:nlevels(fac))[fac.index.by.block.level])
... which I think is something like what you;re after?

S

*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}

```