Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between facet_wrap() and facet_grid() in ggplot2?

I've been reading the ggplot2 documentation for both functions. I was wondering what were the differences and what would be right situation for using each function (facet_wrap() and facet_grid()).

library(ggplot2)  p <- qplot(displ, hwy, data = mpg) p + facet_wrap(~ cyl)  p + facet_grid(~ cyl) 

I provide this small example to serve as starting point. The difference seems to be wrap makes the plots more autonomous and grid makes one plot all together.

like image 387
marbel Avatar asked Dec 08 '13 19:12

marbel


People also ask

What's the difference between Facet_wrap and Facet_grid?

While facet_grid shows the labels at the margins of the facet plot, facet_wrap creates a label for each plot panel.

What does Facet_wrap do in Ggplot?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner.

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data.


1 Answers

The answer below refers to the case when you have 2 arguments in facet_grid() or facet_wrap().

facet_grid(x ~ y) will display x*y plots even if some plots are empty. Ex:

library(ggplot2) g <- ggplot(mpg, aes(displ, hwy)) 

There are 4 distinct cyl and 7 distinct class values.

g + geom_point(alpha=1/3) + facet_grid(cyl~class) 

The above displays 4 * 7 = 28 plots, even if some are empty (because some classes do not have corresponding cylinder values, like rows with class="midsize" doesn't have any corresponding cyl="5" value ) facet_wrap(x ~ y) on the other hand, displays only the plots having actual values.

g + geom_point(alpha=1/3) + facet_wrap(cyl~class) 

There are 19 plots displayed now, one for every combination of cyl and class.

like image 163
Abhijeet Sharma Avatar answered Sep 23 '22 23:09

Abhijeet Sharma