Home > Blockchain >  What is the purpose of using facet_grid(variable ~ .) instead of just using facet_wrap?
What is the purpose of using facet_grid(variable ~ .) instead of just using facet_wrap?

Time:03-10

So I'm self-teaching myself R right now using this online resource: "https://r4ds.had.co.nz/data-visualisation.html#facets"

This particular section is going over the use of facet_wrap and facet_grid. It's clear to me that facet_grid is primarily used when wanting to visualize a plot along two additional dimensions, rather than just one. What I don't understand is why you can use facet_grid(.~variable) or facet_grid(variable~.) to basically achieve the same result as facet_wrap. Putting a "." in place of a variable results in just not faceting along the row or column dimension, or in other words showing 1 additional variable just as facet_wrap would do.

If anyone can shed some light on this, thank you!

CodePudding user response:

If you use facet_grid, the facets will always be in one row/column. They will never wrap to make a rectangle. But really if you just have one variable with few levels, it doesn't much matter.

You can also see that facet_grid(.~variable) and facet_grid(variable~.) will put the facet labels in different places (row headings vs column headings)

mg <- ggplot(mtcars, aes(x = mpg, y = wt))   geom_point()
mg   facet_grid(vs~ .)   labs(title="facet_grid(vs~ .)"),
mg   facet_grid(.~ vs)   labs(title="facet_grid(.~ vs)")  

grid rows vs column

So in the most simple of cases, there's nothing that different between them. The main reason to use facet_grid is to have a single, common axis for all facets so you can easily scan across all panels to make a direct comparison of data.

CodePudding user response:

Actually, the same result is not produced all the time...

The number of facets which appear across the graphs pane is fixed with facet_grid (always the number of unique values in the variable) where as facet_wrap, like its name suggests, wraps the facets around the graphics pane. In this way the functions only result in the same graph when the number of facets produced is small.

Both facet_grid and facet_wrap take their arguments in the form row~columns, and nowdays we don't need to use the dot with facet_grid.

In order to compare their differences let's add a new variable with 8 unqiue values to the mtcars data set:

library(tidyverse)

mtcars$example <- rep(1:8, length.out = 32)

ggplot() 
  geom_point(data = mtcars, aes(x = mpg, y = wt)) 
  facet_grid(~example, labeller = label_both)

Which results in a cluttered plot:

enter image description here

Compared to:

ggplot() 
  geom_point(data = mtcars, aes(x = mpg, y = wt)) 
  facet_wrap(~example, labeller = label_both)

Which results in:

enter image description here

  • Related