Powered by AppSignal & Oban Pro

Grey colour scales: scale_grey

notebooks/scale_grey.livemd

Grey colour scales: scale_grey

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 scale_colour_grey(), which covers scale_fill_grey() 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.

scale_colour_grey() maps a discrete column to evenly spaced shades of grey, the black-and-white counterpart of scale_colour_gradient(). Its start and end give the first shade and the last, from black at 0 to white at 1, and a missing value is drawn red unless na.value says otherwise. scale_fill_grey() does the same for fill. Giggly has Giggly.Plot.scale_color_gray/2 and Giggly.Plot.scale_fill_gray/2, spelt as Giggly's theme, :gray, is, with start:, end: and na_value:. 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.mtcars/0, R's mtcars: 32 cars from the 1974 Motor Trend US magazine, which the setup cell binds to mtcars, R's name for it.

Shades of grey

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point(aes(colour = factor(cyl)))
p + scale_colour_grey()
p + scale_colour_grey(end = 0)

With end = 0 the shades run from dark grey to black, rather than to light grey. Giggly writes factor(cyl) as {:factor, [:cyl]}.

p =
  mtcars
  |> Plot.new(%{x: :mpg, y: :wt})
  |> Plot.geom_point(%{colour: {:factor, [:cyl]}})

p
|> Plot.scale_color_gray()
|> render.()
p
|> Plot.scale_color_gray(end: 0)
|> render.()

A white background

# You may want to turn off the pale grey background with this scale
p + scale_colour_grey() + theme_bw()

theme_bw() is Giggly.Plot.theme_bw/2.

p
|> Plot.scale_color_gray()
|> Plot.theme_bw()
|> render.()

Missing values

sample() gives each car a level from 1 to 5, or a missing value, at random; R draws it without a seed, so it differs from run to run. miss is a vector of its own, not a column of mtcars.

# Colour of missing values is controlled with na.value:
miss <- factor(sample(c(NA, 1:5), nrow(mtcars), replace = TRUE))
ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(colour = miss)) +
  scale_colour_grey()
ggplot(mtcars, aes(mpg, wt)) +
  geom_point(aes(colour = miss)) +
  scale_colour_grey(na.value = "green")

Not in Giggly yet: a vector outside the data in a mapping, here miss.