Scale expansion: expansion
Mix.install([
{:giggly, path: Path.join(__DIR__, "..")},
{:kino, "~> 0.19"}
])
alias Giggly.Plot
mtcars = Giggly.Datasets.mtcars()
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
expansion(), which covers
expand_scale() too, 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.
expansion() builds the value a position scale's expand argument takes: the space left between
the data and the axes, as a multiple of the scale's range (mult), as a fixed amount (add), or
both, either the same at each end or different below and above. expand_scale() is its older
name. Giggly has no expansion(): a position scale's expand: takes the same value as a keyword
list, [mult: {0, 0.1}] for expansion(mult = c(0, .1)), each of mult: and add: one amount
for both ends or a pair, below and above. 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. It binds Giggly.Datasets.mtcars/0, R's mtcars: 32 cars from the 1974 Motor
Trend US magazine, to mtcars, R's name for it.
No space below the bars
# No space below the bars but 10% above them
ggplot(mtcars) +
geom_bar(aes(x = factor(cyl))) +
scale_y_continuous(expand = expansion(mult = c(0, .1)))
The bars stand on the x axis, with a tenth of their range left above the tallest. Giggly writes
factor(cyl) as {:factor, [:cyl]}.
mtcars
|> Plot.new()
|> Plot.geom_bar(%{x: {:factor, [:cyl]}})
|> Plot.scale_y_continuous(expand: [mult: {0, 0.1}])
|> render.()
Space beside discrete values
# Add 2 units of space on the left and right of the data
ggplot(subset(diamonds, carat > 2), aes(cut, clarity)) +
geom_jitter() +
scale_x_discrete(expand = expansion(add = 2))
Not in Giggly yet: geom_jitter().
The default expansion
These are the expansions ggplot2 uses when a scale is given none: 0.6 units at each end of a discrete scale, and 5% of the range at each end of a continuous one.
# Reproduce the default range expansion used
# when the 'expand' argument is not specified
ggplot(subset(diamonds, carat > 2), aes(cut, price)) +
geom_jitter() +
scale_x_discrete(expand = expansion(add = .6)) +
scale_y_continuous(expand = expansion(mult = .05))
Not in Giggly yet: geom_jitter().