phiz

Compare groups with facets

On this page

Split a scatterplot of car weight against fuel economy into one panel for each number of cylinders.

Data

Datasets::mtcars() returns the 32 cars of R’s mtcars data, bundled with phiz as resources/data/mtcars.csv. The example uses three of its columns:

model mpg cyl wt
Mazda RX4 21.0 6 2.620
Mazda RX4 Wag 21.0 6 2.875
Datsun 710 22.8 4 2.320

wt is the weight in thousands of pounds, mpg is the fuel economy in miles per gallon, and cyl is the number of cylinders.

Code

use Phiz\Datasets;use function Phiz\{    aes, facet_wrap, geom_point, ggplot, labs,};$mtcars = Datasets::mtcars();$plot = ggplot($mtcars, aes(x: 'wt', y: 'mpg')) |>    geom_point() |>    facet_wrap('cyl', ncol: 3) |>    labs(x: 'Weight (1,000 lb)', y: 'Miles per gallon');$plot->save('facets.html');
use Phiz\Datasets;use Phiz\Plot;$mtcars = Datasets::mtcars();$plot = Plot::of($mtcars)    ->aes(x: 'wt', y: 'mpg')    ->point()    ->facetWrap('cyl', ncol: 3)    ->labs(x: 'Weight (1,000 lb)', y: 'Miles per gallon');$plot->save('facets.html');

Runnable script: facets.php (PHP 8.5+) or facets.chain.php (PHP 8.3–8.4).

Result

  • Shared scales. By default every panel has the same axis ranges, so positions compare across panels.
  • Free scales. scales: 'free', 'free_x', or 'free_y' gives each panel its own ranges. Positions then no longer compare across panels.
  • Mixed effects. Heavier cars also tend to have more cylinders. Each panel shows the weight and economy association among cars with the same cylinder count.
  • Small groups. The panels hold 11, 7, and 14 cars, so a trend within one panel is a rough description.

In R: ggplot(mtcars, aes(wt, mpg)) + geom_point() + facet_wrap(~cyl, ncol = 3).

See also: facet_wrap() / ->facetWrap() · facet_grid() / ->facetGrid() · geom_point() / ->point() · labs() · Facets and composition