make_constructor: Produce boilerplate constructors

View source: R/make-constructor.R

make_constructorR Documentation

Produce boilerplate constructors

Description

The make_constructor() functions sets up a user-facing constructor for ggproto classes. Currently, make_constructor() is implemented for Geom classes.

Usage

make_constructor(x, ...)

## S3 method for class 'Geom'
make_constructor(
  x,
  ...,
  checks = exprs(),
  omit = character(),
  env = caller_env()
)

## S3 method for class 'Stat'
make_constructor(
  x,
  ...,
  checks = exprs(),
  omit = character(),
  env = caller_env()
)

Arguments

x

An object to setup a constructor for.

...

Name-value pairs to use as additional arguments in the constructor. For layers, these are passed on to layer(params).

checks

A list of calls to be evaluated before construction of the object, such as one constructed with exprs().

omit

A character vector of automatically retrieved argument names that should not be converted to user-facing arguments. Useful for internally computed variables.

env

An environment to search for the object.

Value

A function

Examples

# For testing purposes, a geom that returns grobs
GeomTest <- ggproto(
  "GeomTest", Geom,
  draw_group = function(..., grob = grid::pointsGrob()) {
    return(grob)
  }
)
# Creating a constructor
geom_test <- make_constructor(GeomTest)

# Note that `grob` is automatically an argument to the function
names(formals(geom_test))

# Use in a plot
set.seed(1234)
p <- ggplot(mtcars, aes(disp, mpg))
p + geom_test()
p + geom_test(grob = grid::circleGrob())

# The `checks` argument can be used to evaluate arbitrary expressions in
# the constructor before building the layer.
geom_path2 <- make_constructor(
  GeomPath, checks = rlang::exprs(
    match.arg(lineend, c("butt", "round", "square")),
    match.arg(linejoin, c("round", "mitre", "bevel"))
  )
)

# Note the inclusion of the expressions
print(geom_path2)

# Argument mismatch is detected
try(geom_path2(linejoin = "foo"))

hadley/ggplot2 documentation built on June 13, 2025, 12:51 a.m.