Learn R Programming

ggplot2 (version 4.0.2)

Guide: Guides

Description

The guide_* functions (like guide_legend()) return Guide* objects (like GuideLegend). The Guide* object is responsible for rendering the guide for at least one aesthetic.

Arguments

Details

Each of the Guide* objects is a ggproto() object, descended from the top-level Guide, and each implements various methods and fields.

Building a guide has three stages:

  1. The guide extracts the relevant information from scales.

  2. The guide interacts with other parts of the plot, like coords or layers to supplement information.

  3. The guide is rendered.

When creating a new Guide class, you may want to consider overriding one or more of the following:

  • The params, elements, hashables and available_aes fields.

  • The extract_key(), extract_decor() and extract_params() methods.

  • The transform() or get_layer_key() methods.

  • The setup_params() and override_elements() methods.

  • Any of the build_* methods.

  • As a last resort the measure_grobs(), arrange_layout(), and assemble_drawing() methods.

See Also

Run vignette("extending-ggplot2"), in particular the "Creating new guides" section.

Examples

Run this code
# Extending the class
GuideDescribe <- ggproto(
  "GuideDescribe", Guide,
  # Fields
  elements  = list(text = "legend.text", margin = "legend.margin"),
  hashables = rlang::exprs(key$.label),

  # Methods
  build_title = function(...) zeroGrob(), # Turn off title

  build_labels = function(key, elements, params) {
    labels <- key$.label
    n <- length(labels)
    labels <- paste0(paste0(labels[-n], collapse = ", "), ", and ", labels[n])
    labels <- paste0("A guide showing ", labels, " categories")
    element_grob(elements$text, label = labels, margin_x = TRUE, margin_y = TRUE)
  },

  measure_grobs = function(grobs, params, elements) {
    # Measuring in centimetres is the convention
    width  <- grid::convertWidth(grid::grobWidth(grobs$labels), "cm", valueOnly = TRUE)
    height <- grid::convertHeight(grid::grobHeight(grobs$labels), "cm", valueOnly = TRUE)
    list(width = unit(width, "cm"), height = unit(height, "cm"))
  },

  assemble_drawing = function(self, grobs, layout, sizes, params, elements) {
    gt <- gtable::as.gtable(grobs$labels, width = sizes$width, height = sizes$height)
    gt <- gtable::gtable_add_padding(gt, elements$margin)
    gt
  }
)

# Building a constructor
guide_describe <- function(position = NULL) {
  new_guide(position = position, super = GuideDescribe)
}

# Use new guide plot
ggplot(mpg, aes(displ, hwy, colour = class)) +
  geom_point() +
  guides(colour = guide_describe("bottom"))

Run the code above in your browser using DataLab