Layer points and a fitted line
Plot highway fuel economy against engine displacement, then add a least-squares line with its confidence band.
Data
Datasets::mpg() returns the 234 cars of ggplot2’s mpg data, bundled with phiz as resources/data/mpg.csv. The example uses two of its columns:
| displ | hwy |
|---|---|
| 1.8 | 29 |
| 1.8 | 29 |
| 2.0 | 31 |
displ is the engine displacement in liters, and hwy is the highway fuel economy in miles per gallon.
Code
use Phiz\Datasets;use function Phiz\{ aes, geom_point, geom_smooth, ggplot, labs,};$mpg = Datasets::mpg();$plot = ggplot($mpg, aes(x: 'displ', y: 'hwy')) |> geom_point(alpha: 0.5) |> geom_smooth(method: 'lm') |> labs( x: 'Engine displacement (L)', y: 'Highway miles per gallon', );$plot->save('layers.html');use Phiz\Datasets;use Phiz\Plot;$mpg = Datasets::mpg();$plot = Plot::of($mpg) ->aes(x: 'displ', y: 'hwy') ->point(alpha: 0.5) ->smooth(method: 'lm') ->labs( x: 'Engine displacement (L)', y: 'Highway miles per gallon', );$plot->save('layers.html');Runnable script: layers.php (PHP 8.5+) or layers.chain.php (PHP 8.3–8.4).
Result
- Inheritance. Both layers use the data and the
xandymappings given toggplot(). A layer’s own mappings or data override them. - The band. The band is a 95% confidence interval for the mean response, not a prediction interval for individual cars.
- R parity. phiz computes the line and the band in PHP. They match R’s
predict(fit, interval = "confidence"). - Straight line. The points rise again at the largest displacements, which a straight line cannot follow. The default method, loess, fits a local curve (Fitted curves).
- Association. Cars with larger engines tend to have lower highway economy in this data. The line describes that association, not the effect of changing a car’s engine.
In R: ggplot(mpg, aes(displ, hwy)) + geom_point(alpha = 0.5) + geom_smooth(method = "lm").
See also: ggplot() · aes() · geom_point() / ->point() · geom_smooth() / ->smooth() · labs() · save()