[R] ggplot2 - facetting

hadley wickham h.wickham at gmail.com
Tue Mar 25 16:13:18 CET 2008


On Tue, Mar 25, 2008 at 9:49 AM, Pedro de Barros <pbarros at ualg.pt> wrote:
> Dear All,
>
>  After having overcome the issue of legends (thanks, Thierry, once
>  more), I am trying to use facetting, but here also I can not find how
>  to do this. I do not want to use qplot, but rather the more flexible
>  options. However, it seems I am doing still something pretty stupid,
>  because I always get an error, even if it seems I am doing everything
>  like the examples.
>
>  My code is below.
>  set.seed(123)
>  plotdata2<-data.frame(x=rep((1:4),4), y=rep(0.1*(1:4),4),
>  group=sample(factor(rep(1:4,rep(4,4)), labels=c('Class1', 'Class2',
>  'Class3', 'Class4'))))
>  plotdata2 <- plotdata2[order(plotdata2[,'group']),]
>  plot0<-ggplot()
>  layer1<-layer(data=plotdata2,
>  mapping=aes_string(x='x',y='y'),geom='point', stat='identity')
>  scaleY<-scale_y_continuous()
>  scaleX <- scale_x_continuous()
>  Facets<-facet_grid(group ~ .)
>  plot1<-plot0+layer1 +scaleY + scaleX + facet_grid(group~.)
>
>  plot1
>
>  I always get the error message:
>  Error in check_formula(formula, varnames) :
>    Formula contains variables not in list of known variables
>
>  Thanks for any help you can provide.

Hi Pedro,

To do facetting, there needs to be a default dataset for the plot:

plot0<-ggplot(plotdata2)

I'd also suggest you use some of the defaults:

layer1 <- geom_point(aes(x=x, y=y))
plot0 + layer1 + facet_grid(group~.)

(scales will be automatically added)

or with qplot:

qplot(x, y, data=plotdata2, facets = group ~ .)

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list