Powered by AppSignal & Oban Pro

Legends: guide_legend

notebooks/guide_legend.livemd

Legends: guide_legend

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 guide_legend(), 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.

guide_legend() draws a legend: for each of a scale's breaks, a key drawn as the layer's geom draws it, beside a label. It is chosen in a scale's guide argument or in guides(), and the legends of several scales are merged into one where they can be. Its options set the title, the number of rows or columns, the order of the keys and the aesthetics they are drawn with, and, through a theme of its own, where the title and labels go and how they look. Giggly has Giggly.Plot.guide_legend/1, chosen in a scale's guide: or in Giggly.Plot.guides/2, with its reverse: option alone, and reads alpha, and a discrete colour or fill, back with a legend by default, merging those with one title and the same labels. 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.

The basic form

expand.grid() makes a row for every pair of X1 and X2 from 1 to 10, and value is their product. A continuous fill is read back by a colour bar by default; guide_legend() gives it a key for each break instead.

df <- expand.grid(X1 = 1:10, X2 = 1:10)
df$value <- df$X1 * df$X2

p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p2 <- p1 + geom_point(aes(size = value))

# Basic form
p1 + scale_fill_continuous(guide = guide_legend())

The cell builds the same table, X1 changing fastest, as expand.grid() builds it. p2, which adds points sized by value, is drawn by no example.

pairs = for x2 <- 1..10, x1 <- 1..10, do: {x1, x2}

df = %{
  "X1" => Enum.map(pairs, fn {x1, _x2} -> x1 end),
  "X2" => Enum.map(pairs, fn {_x1, x2} -> x2 end),
  "value" => Enum.map(pairs, fn {x1, x2} -> x1 * x2 end)
}

p1 =
  df
  |> Plot.new(%{x: :X1, y: :X2})
  |> Plot.geom_tile(%{fill: :value})

p1
|> Plot.scale_fill_continuous(guide: Plot.guide_legend())
|> render.()

Styling the title and labels

A guide's theme styles only that guide: here the title to the left of the keys, a large red italic title, and labels to the left of the keys, aligned right. In the first plot the theme is guide_legend()'s second argument, given without its name.

# Control styles

# title position
p1 + guides(fill = guide_legend(
  title = "LEFT", theme(legend.title.position = "left")
))

# title text styles via element_text
p1 + guides(fill = guide_legend(theme = theme(
  legend.title = element_text(size = 15, face = "italic", colour = "red")
)))

# label position
p1 + guides(fill = guide_legend(theme = theme(
  legend.text.position = "left",
  legend.text = element_text(hjust = 1)
)))

Not in Giggly yet: guide_legend()'s title and theme options, and the theme's legend.title.position and legend.text.position settings.

A horizontal legend

# label styles
p1 +
  scale_fill_continuous(
    breaks = c(5, 10, 15),
    labels = paste("long", c(5, 10, 15)),
    guide = guide_legend(theme = theme(
      legend.direction = "horizontal",
      legend.title.position = "top",
      legend.text.position = "bottom",
      legend.text = element_text(hjust = 0.5, vjust = 1, angle = 90)
    ))
  )

The keys run across, with the title above them and each label below its key, turned on its side.

Not in Giggly yet: guide_legend()'s theme option, and the theme's legend.title.position and legend.text.position settings.

Keys drawn opaque

# Set aesthetic of legend key
# very low alpha value make it difficult to see legend key
p3 <- ggplot(mtcars, aes(vs, am, colour = factor(cyl))) +
  geom_jitter(alpha = 1/5, width = 0.01, height = 0.01)
p3
# override.aes overwrites the alpha
p3 + guides(colour = guide_legend(override.aes = list(alpha = 1)))

Keys are drawn as the layer draws its points, here almost transparent; override.aes draws them with an alpha of their own. Giggly draws the first plot, writing factor(cyl) as {:factor, [:cyl]}; its points are jittered by Erlang's random numbers, not R's, so they land elsewhere than ggplot2's, each within the same 0.01 of its place (geom_jitter()'s notebook says more).

p3 =
  mtcars
  |> Plot.new(%{x: :vs, y: :am, colour: {:factor, [:cyl]}})
  |> Plot.geom_jitter(alpha: 0.2, width: 0.01, height: 0.01)

render.(p3)

Not in Giggly yet: guide_legend()'s override.aes option.

Rows and columns of keys

# multiple row/col legends
df <- data.frame(x = 1:20, y = 1:20, color = letters[1:20])
p <- ggplot(df, aes(x, y)) +
  geom_point(aes(colour = color))
p + guides(col = guide_legend(nrow = 8))
p + guides(col = guide_legend(ncol = 8))
p + guides(col = guide_legend(nrow = 8, theme = theme(legend.byrow = TRUE)))

legend.byrow = TRUE fills the keys in row by row, rather than column by column.

Not in Giggly yet: guide_legend()'s nrow, ncol and theme options, and the theme's legend.byrow setting.

Keys in reverse order

# reversed order legend
p + guides(col = guide_legend(reverse = TRUE))

p is the example above's plot, twenty points coloured by the first twenty letters, R's letters[1:20], which the cell makes too. R's col is short for colour. The legend's keys run from t down to a.

df = %{
  "x" => Enum.to_list(1..20),
  "y" => Enum.to_list(1..20),
  "color" => ~w(a b c d e f g h i j k l m n o p q r s t)
}

p =
  df
  |> Plot.new(%{x: :x, y: :y})
  |> Plot.geom_point(%{colour: :color})

p
|> Plot.guides(colour: Plot.guide_legend(reverse: true))
|> render.()