# [R] Colors in interaction plots

Iuri Gavronski iuri at ufrgs.br
Thu Jan 17 13:28:47 CET 2013

```Hi,

I am trying to plot an interaction.plot with different color for each
level of a factor. It has an erratic behavior.

For example, it works for the first interaction.plot below, with the
example from the ALDA book, but not with the other plots, from the NPK
dataset:

# from http://www.ats.ucla.edu/stat/r/examples/alda/ch2.htm
tolerance.pp <-
attach(tolerance.pp)
# fitting the linear model by id
fit <- by(tolerance.pp, id, function(bydata)
fitted.values(lm(tolerance ~ time, data=bydata)))
fit <- unlist(fit)

# plotting the linear fit by id
interaction.plot(age, id, fit, xlab="age", ylab="tolerance")

# plots red for female and green for male
interaction.plot(age, id, fit, xlab="age", ylab="tolerance", col=male+2)

print(tolerance.pp[id==978|id==514|id==9|id==1105|id==1653,c("id","male")])

data(npk, package="MASS")
fit <- by(npk, npk\$block, function(bydata) fitted.values(lm(yield ~ N,
data=bydata)))
fit <- unlist(fit)
interaction.plot(npk\$N, npk\$block, fit, xlab="N", ylab="yield")
# fake factor, numeric
fac <- c(rep(1,12),rep(2,12))
# plots everything in black
interaction.plot(npk\$N, npk\$block, fit, xlab="N", ylab="yield",col=fac)
cbind(npk\$block,fac)
# plots everything transparent
fac <- as.factor(fac)
interaction.plot(npk\$N, npk\$block, fit, xlab="N",
ylab="yield",col=as.numeric(npk\$fac))

```