11

Possible Duplicate:
ggplot - facet by function output

ggplot2's facets option is great for showing multiple plots by factors, but I've had trouble learning to efficiently convert continuous variables to factors within it. With data like:

DF <- data.frame(WindDir=sample(0:180, 20, replace=T), 
                 WindSpeed=sample(1:40, 20, replace=T), 
                 Force=sample(1:40, 20, replace=T))
qplot(WindSpeed, Force, data=DF, facets=~cut(WindDir, seq(0,180,30)))

I get the error : At least one layer must contain all variables used for facetting

I would like to examine the relationship Force~WindSpeed by discrete 30 degree intervals, but it seems facet requires factors to be attached to the data frame being used (obviously I could do DF$DiscreteWindDir <- cut(...), but that seems unecessary). Is there a way to use facets while converting continuous variables to factors?

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
Señor O
  • 17,049
  • 2
  • 45
  • 47
  • 2
    Why not just do the converting first, i.e. `DF$WindDirBin = cut(DF$WindDir, seq(0,180,30))`, and then `facets=~WindDirBin` – David Robinson Jan 28 '13 at 19:24
  • I mentioned that I could do that in my question. I would prefer another solution because (a) the data frame I'm using already has 28 columns and I'd prefer not to add more that don't contain additional information and (b) there are several variables within that data frame I need to do this to, so it's much easier to use `cut` in an ad hoc basis, like with `by(DF[,c('WindSpeed', 'Force')], cut(DF$WindDir, seq(0,180,30)), plot)` – Señor O Jan 28 '13 at 19:33
  • ^ Thanks for finding that. That's not the answer I was looking for but I think that answer the question well enough. `transform` seems to be the best option. – Señor O Jan 28 '13 at 20:00

1 Answers1

9

Making an example of how you can use transform to make an inline transformation:

qplot(WindSpeed, Force,
      data = transform(DF,
                       fct = cut(WindDir, seq(0,180,3))),
      facets=~fct)

You don't "pollute" data with the faceting variable, but it is in the data frame for ggplot to facet on (rather than being a function of columns in the facet specification).

This works just as well in the expanded syntax:

ggplot(transform(DF,
                 fct = cut(WindDir, seq(0,180,3))),
       aes(WindSpeed, Force)) +
  geom_point() +
  facet_wrap(~fct)
Brian Diggs
  • 57,757
  • 13
  • 166
  • 188