Skip to content

Allow scale name to be a function.  #4313

Closed
@eliocamp

Description

@eliocamp

I think it might be useful to have the possibility of passing a function to scale names like so:

library(ggplot2)

df <- expand.grid(X1 = 1:10, X2 = 1:10)
df$value <- df$X1 * df$X2
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))

p1 + scale_fill_continuous(function(x) base::toupper(x))

# With function shorthand
p1 + scale_fill_continuous(~ base::toupper(.x))

Created on 2021-01-11 by the reprex package (v0.3.0)

Something like this would make code snippets more portable. In my case, I have a function that makes a plot and I had to define the title outside the plot depending on the function arguments. With this, I could've defined a global dictionary which translates column names to actual (human readable) variable names and re-use that all over my report.

To produce the code above I just added this

  if (is.formula(name)) {
    name <- as_function(name)
  }

  if (is.function(name)) {
    make_title <- name
    name <- waiver()
  } else {
    make_title <- super$make_title
  }

before this line:

https://github.com/tidyverse/ggplot2/blob/master/R/scale-.r#L107

And then added make_title = make_title to the ggproto construction.

All tests pass, so changing this should be safe.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions