19.9 Adding guides

The legend (legend_box) is first defined in Step 11:

body(ggplot2:::ggplot_gtable.ggplot_built)[[11]]
title_height <- grobHeight(title)
legend_box <- ggtrace_inspect_vars(
  x = p, method = ggplot2:::ggplot_gtable.ggplot_built,
  at = 12, vars = "legend_box"
)
grid.newpage()
grid.draw(legend_box)

It then undergoes some edits/tweaks, including resolving the legend.position theme setting, and then finally gets added to the plot in Step 15:

body(ggplot2:::ggplot_gtable.ggplot_built)[[15]]
caption_height <- grobHeight(caption)
p_with_legend <- ggtrace_inspect_vars(
  x = p, method = ggplot2:::ggplot_gtable.ggplot_built,
  at = 16, vars = "plot_table"
)
grid.newpage()
grid.draw(p_with_legend)

The bulk of the work was done in Step 11, with the build_guides() function. That in turn calls guides_train() and guides_gengrob() which in turn calls guide_train() and guide_gengrob for each scale (including positional aesthetics like x and y).

  • Why scale? The scale is actually what holds information about guide. They’re two sides of the same coin - the scale translates the underlying data to some defined space, and the guide reverses that (translates a space to data). One’s for drawing, the other is for reading.

  • This is also why all scale_*() functions take a guide argument. Positional scales use guide_axis() as default, and non-positional scales use guide_legend() as default.

class(guide_legend())
[1] "GuideLegend" "Guide"       "ggproto"     "gg"         
# This explicitly spells out the default
p +
  scale_color_discrete(guide = guide_legend())

This is the output of the guide_train() method defined for guide_legend(). The most important piece of it is key, which is the data associated with the legend.

The output of guide_train() is passed to guide_gengrob(). This is the output of the guide_gebgrob() method defined for guide_legend():