Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Unused Factors from a Facet in ggplot2

Tags:

r

ggplot2

I am trying to figure out a neat way to remove unused factors from a facet in ggplot2. Here is a minimal example

# DUMMY DATA
mydf = data.frame(
  x = rpois(6, 25),
  y = LETTERS[1:6],
  cat = c(rep('AA', 3), rep('BB', 3)))

# PLOT IT!
p0 = ggplot(mydf, aes(x = x, y = y)) +
  geom_point() +
  facet_wrap(~ cat, ncol = 1)

From the plot below, you can see that factors D, E and F are plotted in facet AA despite the fact that there is no corresponding data. What I want is for a way to eliminate {D, E, F} from facet AA and similarly {A, B, C} from facet BB.

Is there a neat way to do this, or even a hack would be acceptable.

enter image description here

like image 253
Ramnath Avatar asked Aug 11 '11 19:08

Ramnath


People also ask

How to remove label from facet plot in ggplot2?

We can customize various aspects of a ggplot2 using the theme () function. To remove the label from facet plot, we need to use “strip.text.x” argument inside the theme () layer with argument ‘element_blank ()’. Writing code in comment?

How to facet continuous variables in ggplot2?

Another useful technique is to put all the data in the background of each panel: To facet continuous variables, you must first discretise them. ggplot2 provides three helper functions to do so:

How do you plot a facet plot in Python?

Facet plots, where one subsets the data based on a categorical variable and makes a series of similar plots with the same scale. We can easily plot a facetted plot using the facet_wrap () function of the ggplot2 package.

What is the difference between facet_wrap and facet-variable in ggplot2?

When we use facet_wrap () in ggplot2, by default it gives a title to each plot according to the group they are divided into. facet-variable: Determines the variable around which plots have to be divided.


1 Answers

I think all you need is scales = "free_y":

p0 = ggplot(mydf, aes(x = x, y = y)) +
  geom_point() +
  facet_wrap(~ cat, ncol = 1,scales = "free_y")

p0

enter image description here

like image 178
joran Avatar answered Sep 23 '22 10:09

joran