Powered by AppSignal & Oban Pro

Jittered points: geom_jitter

notebooks/geom_jitter.livemd

Jittered points: geom_jitter

Mix.install([
  {:giggly, path: Path.join(__DIR__, "..")},
  {:kino, "~> 0.19"}
  ])

alias Giggly.Plot

mpg = Giggly.Datasets.mpg()

render = fn plot ->
  plot
  |> Giggly.to_svg()
  |> IO.iodata_to_binary()
  |> Kino.Image.new(:svg)
end

About this notebook

This notebook follows the examples on ggplot2's reference page for geom_jitter(), in the order the page gives them. Each example shows ggplot2's code first and then Giggly's. An example Giggly cannot draw yet keeps its ggplot2 code and names what it is waiting for, so the page is also a list of what remains.

geom_jitter() is a shortcut for geom_point(position = "jitter"): it moves each point by a small random amount, so that points which would sit on one another, as discrete values make them do, can be told apart. Giggly has no jitter yet, neither geom_jitter() nor position_jitter(); it draws the same points unmoved, with Giggly.Plot.geom_point/3. A plot is described with Giggly.Plot and drawn with Giggly.to_svg/2, which returns an SVG document. The setup cell aliases Giggly.Plot, so the cells write Plot.new/2, and defines render, which draws a plot and shows it below the cell with Kino.Image. The data in these examples is Giggly.Datasets.mpg/0, ggplot2's mpg: fuel economy for 234 cars of 38 popular models from 1999 to 2008, which the setup cell binds to mpg, ggplot2's name for it.

Points without jitter

p <- ggplot(mpg, aes(cyl, hwy))
p + geom_point()

Many cars share both a number of cylinders and a highway mileage, so their points are drawn on top of one another.

mpg
|> Plot.new(%{x: :cyl, y: :hwy})
|> Plot.geom_point()
|> render.()

Jittered points

p + geom_jitter()

Not in Giggly yet: geom_jitter() and the position it adds, position_jitter().

Mapping colour

# Add aesthetic mappings
p + geom_jitter(aes(colour = class))

Not in Giggly yet: geom_jitter().

Less jitter

# Use smaller width/height to emphasise categories
ggplot(mpg, aes(cyl, hwy)) +
  geom_jitter()
ggplot(mpg, aes(cyl, hwy)) +
  geom_jitter(width = 0.25)

Unless told otherwise, the jitter moves a point up to 40% of the data's resolution either way; a smaller width keeps each number of cylinders in a narrower column.

Not in Giggly yet: geom_jitter() and its width option.

More jitter

# Use larger width/height to completely smooth away discreteness
ggplot(mpg, aes(cty, hwy)) +
  geom_jitter()
ggplot(mpg, aes(cty, hwy)) +
  geom_jitter(width = 0.5, height = 0.5)

Not in Giggly yet: geom_jitter() and its width and height options.