Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facet for continuous variables in ggplot2 [duplicate]

Tags:

r

ggplot2

facet

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?

like image 328
Señor O Avatar asked Jan 28 '13 19:01

Señor O


People also ask

What is facet in ggplot2?

The facet approach partitions a plot into a matrix of panels. Each panel shows a different subset of the data. This R tutorial describes how to split a graph using ggplot2 package. There are two main functions for faceting : facet_grid()

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.

What does facet wrap mean in R?

Facet wraps are a useful way to view individual categories in their own graph. For example, if you wanted to make a separate graph for each cut measuring the price (y axis) for each clarity (x axis), you could add facet_wrap(~cut) .


1 Answers

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)
like image 175
Brian Diggs Avatar answered Oct 23 '22 14:10

Brian Diggs