Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

r - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...