33
$\begingroup$

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?

$\endgroup$
1
  • $\begingroup$ For pure programming (not stats) questions like this, please migrate to StackOverflow $\endgroup$
    – smci
    Sep 13, 2018 at 7:01

1 Answer 1

40
$\begingroup$

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")
$\endgroup$
4
  • $\begingroup$ 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? $\endgroup$
    – mrrrau
    Mar 17, 2012 at 16:30
  • $\begingroup$ @mrrrau Yes, see my edit. $\endgroup$
    – joran
    Mar 17, 2012 at 16:51
  • 33
    $\begingroup$ 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. $\endgroup$ Jun 21, 2016 at 19:45
  • $\begingroup$ @JakeFisher Thanks for pointing this out! Quite helpful! $\endgroup$
    – Steven
    May 21, 2017 at 16:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.