Drop unused levels in facet_wrap in ggplot2

Viewed 226

I am needing to drop unused levels in facet_wrap (ggplot2), but can't figure out how to do it. The initial question was posted here, but thought this would be better as a separate question.

Here is some example code:

group1 = c(rep("A",4),rep("B",4),rep("C",3))
group2 = c(rep(c("param1","param2","param3","param4"),2),c("param1","param2","param3"))
est = rnorm(length(group2),mean = 0, sd = 1)
lwr = est - sd(est)
upr = est + sd(est)

df = data.frame(group1,group2,est,lwr,upr)

# Swapped the x axis to use group1
figure.gg = ggplot(data = df, aes(x = group1, y = est, ymin = lwr, ymax = upr)) +
  geom_point(position = position_dodge(width = 0.5)) +
  geom_errorbar(position = position_dodge(width = 0.5), width = 0.1) +
  coord_flip() +
  # Facet wrapped with one column using group 2s
  facet_wrap(~group2, ncol = 1, strip.position = "right") +
  ylab("estimate")

figure.gg

Group1 (C) does not have a param4, but it is included in the figure. However, adding drop = TRUE to facet_wrap() does not change the behavior. I can solve with scales = "free_x", but I really don't want to float the facets; I want them to all be aligned.

1 Answers

Specify scales = "free_y"

figure.gg = ggplot(data = df, aes(x = group1, y = est, ymin = lwr, ymax = upr)) +
  geom_point(position = position_dodge(width = 0.5)) +
  geom_errorbar(position = position_dodge(width = 0.5), width = 0.1) +
  coord_flip() +
  # Facet wrapped with one column using group 2s
  facet_wrap(~group2, ncol = 1, strip.position = "right", scales = "free_y") +
  ylab("estimate")

figure.gg
Related