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?
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()
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.
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) .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With