28

Is it possible to drop levels that are not used in ggplot2s facets? This is my code:

tab = as.data.frame(cbind(groups = mtcars$cyl, names = row.names(mtcars), val = mtcars$mpg, N = mtcars$disp))
tab$N = as.numeric(tab$N)

ggplot(tab, aes(names,val)) + 
geom_point() + coord_flip() + 
theme_bw() + 
facet_grid(groups ~ ., drop=TRUE)#, scales="free", as.table=F, space="free")

I tried the drop=T switch but it doesnt help. What am I doing wrong?

Ferdi
  • 4,882
  • 7
  • 42
  • 62
mrrrau
  • 395
  • 1
  • 3
  • 4
  • For pure programming (not stats) questions like this, please migrate to StackOverflow – smci Sep 13 '18 at 07:01

1 Answers1

36

Your example data just doesn't have any unused levels to drop. Check the behavior in this example:

dat <- data.frame(x = runif(12),
                  y = runif(12),
                  grp1 = factor(rep(letters[1:4],times = 3)),
                  grp2 = factor(rep(LETTERS[1:2],times = 6)))

levels(dat$grp2) <- LETTERS[1:3]

ggplot(dat,aes(x = x,y = y)) + 
    facet_grid(grp1~grp2,drop = FALSE) + 
    geom_point()

ggplot(dat,aes(x = x,y = y)) + 
    facet_grid(grp1~grp2,drop = TRUE) + 
    geom_point()

It may be that you're looking to change which factors are plotting on the vertical axis in each facet, in which case you want to set the scales argument and use facet_wrap:

ggplot(tab, aes(names,val)) + 
    geom_point() + coord_flip() + 
    theme_bw() + 
    facet_wrap(~groups,nrow = 3,scales = "free_x")
joran
  • 1,208
  • 11
  • 17
  • Oh i see now what it does. My intention was to plot only those levels in every facet, that are actually grouped by the facet. Like, using my tab example,`dotchart(as.numeric(tab$val), labels=tab$names, groups=tab$groups)`. Is it possible? – mrrrau Mar 17 '12 at 16:30
  • @mrrrau Yes, see my edit. – joran Mar 17 '12 at 16:51
  • 28
    For future readers, `drop` drops any factor levels that weren't used in *any* facet of the plot, while `scales` drops any factor level that wasn't used in a particular facet of the plot. This took me a while to understand from this post, so I thought I'd clarify here to save someone else the trouble. – Jake Fisher Jun 21 '16 at 19:45
  • @JakeFisher Thanks for pointing this out! Quite helpful! – Steven May 21 '17 at 16:44