ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Manual stat

Open teunbrand opened this issue 1 year ago • 0 comments

This PR aims to fix #3501 and replaces #6066.

It improves upon #6066 by simplifying the stat to stat_manual(fun = identity). It really is a thin wrapper to essentially offer a way for a user to provide an arbitrary Stat$compute_group() method.

A nice thing is that you can still do NSE with transform()/with() or dplyr verbs like mutate()/reframe()/summarise(). Base NSE requires providing args as quotes and tidyverse NSE can use vars().

The examples rendered:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2

# A standard scatterplot
p <- ggplot(mtcars, aes(disp, mpg, colour = factor(cyl))) +
  geom_point()

# The default just displays points as-is
p + stat_manual()

# Using a custom function
make_hull <- function(data) {
  hull <- chull(x = data$x, y = data$y)
  data.frame(x = data$x[hull], y = data$y[hull])
}

p + stat_manual(
  geom = "polygon",
  fun  = make_hull,
  fill = NA
)

# Using the `with` function with quoting
p + stat_manual(
  fun  = with,
  args = list(expr = quote({
    hull <- chull(x, y)
    list(x = x[hull], y = y[hull])
  })),
  geom = "polygon", fill = NA
)

# Using the `transform` function with quoting
p + stat_manual(
  geom = "segment",
  fun  = transform,
  args = list(
    xend = quote(mean(x)),
    yend = quote(mean(y))
  )
)

# Get centroids with `summarise()`
p + stat_manual(
  size = 10, shape = 21,
  fun  = dplyr::summarise,
  args = vars(x = mean(x), y = mean(y))
)

# Connect to centroid with `mutate`
p + stat_manual(
  geom = "segment",
  fun  = dplyr::mutate,
  args = vars(xend = mean(x), yend = mean(y))
)

# Computing hull with `reframe()`
p + stat_manual(
  geom = "polygon", fill = NA,
  fun  = dplyr::reframe,
  args = vars(hull = chull(x, y), x = x[hull], y = y[hull])
)

Created on 2024-09-13 with reprex v2.1.1

teunbrand avatar Sep 13 '24 11:09 teunbrand