Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@
* `theme(strip.placement.x)` and `theme(strip.placement.y)` can be used for more
granular control of strip placement when facetting. These have existed for some
time but were not previously documented (@arcresu, #6827).
* The example in `?ggproto` now demonstrates a stateless class,
with additional guidance noting that most ggplot2 layer classes
are stateless (@CuiweiG, #6582).

# ggplot2 4.0.2

Expand Down
36 changes: 19 additions & 17 deletions R/ggproto.R
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@
#' ['modify in place'](https://adv-r.hadley.nz/names-values.html#env-modify)
#' semantics.
#'
#' In practice, most ggplot2 layer classes (Geoms, Stats, Scales) are
#' stateless: their methods read from arguments rather than from
#' `self` fields. Extension authors are encouraged to follow this
#' pattern, reserving stateful fields for cases where a method
#' genuinely needs to track values across calls.
#'
#' @param _class Class name to assign to the object. This is stored as the class
#' attribute of the object. This is optional: if `NULL` (the default),
#' no class name will be added to the object.
Expand All @@ -45,25 +51,21 @@
#' The `r link_book("ggproto introduction section", "internals#sec-ggproto")`
#' @export
#' @examples
#' Adder <- ggproto("Adder",
#' x = 0,
#' add = function(self, n) {
#' self$x <- self$x + n
#' self$x
#' }
#' )
#' is_ggproto(Adder)
#'
#' Adder$add(10)
#' Adder$add(10)
#' # A stateless class with static methods (no use of `self` fields):
#' Math <- ggproto("Math",
#' double = function(n) n * 2,
#' square = function(n) n * n
#' )
#' is_ggproto(Math)
#' Math$double(5)
#' Math$square(5)
#'
#' Doubler <- ggproto("Doubler", Adder,
#' add = function(self, n) {
#' ggproto_parent(Adder, self)$add(n * 2)
#' }
#' # Inheritance: child overrides parent. `self` is threaded only to call
#' # `ggproto_parent()` — the class remains stateless (no `self$*` access).
#' Mather <- ggproto("Mather", Math,
#' square = function(self, n) ggproto_parent(Math, self)$double(n) * n
#' )
#' Doubler$x
#' Doubler$add(10)
#' Mather$square(5)
ggproto <- function(`_class` = NULL, `_inherit` = NULL, ...) {
e <- new.env(parent = emptyenv())

Expand Down
36 changes: 19 additions & 17 deletions man/ggproto.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading