Question

I use the effects package in R to generate nice effects plots. When one of the predictors in my model is a factor, the plot uses the factor labels as axis tick labels. In some cases this is not ideal, since the factor names may be shortened for ease of typing and viewing in Anova displays, but I'd like a more readable label for the plot.

I tried using the transform.x argument to plot, but the documentation says this only works for "numeric predictors", and indeed it doesn't seem to work (there is no effect on the displayed labels).

I specifically do not want to change the factor level names themselves (i.e., change the data), because I have other reasons for wanting them to be what they are. I only want to affect the plot display, not the model itself.

What I want is the ability to specify a mapping between factor levels of a predictor and strings to be used as the axis tick labels for those factor levels. How can I achieve this?

Here is a simple example:

library(effects)
A = rnorm(100)
B = rnorm(100)
C = factor(rep(c("This", "That"), 50))
model = lm(A~B*C)
plot(effect("B:C", model), x.var="C")

That produces this plot:

effect plot http://snag.gy/5mTkJ.jpg

I want to be able to change the x-axis tick labels "This" and "That" to anything I want, without changing the actual factor level names in the vector C.

Was it helpful?

Solution

Unfortunately, there's no direct way. Have a look at the plotting function: getAnywhere("plot.eff").

Here's a workaround:

First create the effect object:

ef <- effect("B:C", model) 

Modify the levels of C in ef:

ef$variables$C$levels <- c("foo", "bar")
levels(ef$x$C) <- c("foo", "bar")

Plot:

plot(ef, x.var = "C")

enter image description here

OTHER TIPS

This is not an answer but an explanation why is difficult here to change the axis labels without changing the factor levels.

You can see the S3 method plot of eff objects ( class eff). To get the code source plot function of object of type eff You can do something like:

getS3method('plot','eff')

the plot is basically an xyplot ( a lattice scatter plot).

the relevant part is :

levs <- levels(x[, 1])
plot <- xyplot(....,scales = list(x = list(at = 1:length(levs), 
                                               labels = levs, rot = rotx),..)

the labels are hard coded as the levels of the factor.

Hopefully, the function can be easily enhanced using something like this(maybe you can contact package maintainer)

 levs <- arg.levels      ## new levels arguments given as an argument
 if(is.null(levs))
    levs <- levels(x[, 1])

the problem there are many calls to xyplot, so you have to change scales argument many times...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top