Facetting with ggplot

Code snippet to play with facetting a ggplot.

A reduced version of {starwars} will be the toy dataset:

all

Classical Facetting:

 ggplot(starwars.light) +
   geom_point(aes(x = height, y = mass, col = species), size = 2.5) +
   facet_wrap(~species)

classical_facets

Facetting with an ALL facet:

 ggplot(starwars.light) +
   geom_point(aes(x = height, y = mass, col = species), size = 2.5, data = starwars.light) +
   geom_point(aes(x = height, y = mass, col = starwars.light$species), size = 2.5, data = transform(starwars.light, species = 'All')) +
   facet_wrap(~species)

classical_all_facets

Two way facetting:

Note that I changed facet_wrap() to facet_grid()

 ggplot(starwars.light) +
   geom_point(aes(x = height, y = mass, col = gender), size = 2.5) +
   facet_grid(gender~species)

two_way_facets

To add an (all) margin to the plot, just add margin = TRUE in the facet_grid

 ggplot(starwars.light) +
   geom_point(aes(x = height, y = mass, col = gender), size = 2.5) +
   facet_grid(gender~species, margin = TRUE)

two_way_facets_w_margin

Highlighting with ggplot

The trick here, consist to initialize the ggplot space with a dataset without the categorical information (here, species):

all_no_species

Facetting with highlighting:

 ggplot(select(starwars.light, -species)) +
   geom_point(aes(x = height, y = mass), size = 2.5, col = 'gray') +
   geom_point(aes(x = height, y = mass, col = species), size = 2.5, data = starwars.light) +
   facet_wrap(~species)

highlight_facets

Facetting with highlighting and all panel:

 ggplot(select(starwars.light, -species)) +
   geom_point(aes(x = height, y = mass), size = 2.5, col = 'gray') +
   geom_point(aes(x = height, y = mass, col = species), size = 2.5, data = starwars.light) +
   geom_point(aes(x = height, y = mass, col = starwars.light$species), size = 2.5, data = transform(starwars.light, species = 'All')) +
   facet_wrap(~species)

highlight_all_facets

Two way highlighting:

Note that I changed facet_wrap() to facet_grid()

 ggplot(select(starwars.light, -gender)) +
   geom_point(aes(x = height, y = mass), size = 2.5, col = 'gray') +
   geom_point(aes(x = height, y = mass, col = gender), size = 2.5, data = starwars.light) +
   facet_grid(gender~species)

two_way_facets

To add an (all) margin to the plot, just add margin = TRUE in the facet_grid

 ggplot(select(starwars.light, -gender)) +
   geom_point(aes(x = height, y = mass), size = 2.5, col = 'gray') +
   geom_point(aes(x = height, y = mass, col = gender), size = 2.5, data = starwars.light) +
   facet_grid(gender~species, margin = TRUE)

two_way_facets_w_margin