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

ぃ、小莉子 提交于 2019-12-02 16:56:28
Abhijeet Sharma

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.

facet_wrap(...) strings together ggplots in different frames (facets) based in a single variable. facet_grid(...) can take two variables:

p + facet_grid(cyl~class)

You can also use a third variable to group in each facet:

qplot(displ, hwy, data=mpg,color=factor(year)) + facet_grid(cyl~class)

shows the improvement (or lack thereof) in hwy mileage vs. displacement by #cylinders and class.

Chris Baskerville

For single variable plots you can use either facet_grid() or facet_wrap().

facet_wrap(~variable) will return a symmetrical matrix of plots for the number of levels of variable.

facet_grid(.~variable) will return facets equal to the levels of variable distributed horizontally.

facet_grid(variable~.) will return facets equal to the levels of variable distributed vertically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!