问题
I can call an anonymous function in scale_y_continuous() using function(y) comma(y)
, but I cannot call an anonymous function using the ~ convention. Is it possible to use ~ in this situation?
library(scales)
library(ggplot2)
mtcars$model <- rownames(mtcars)
# Success
ggplot(mtcars[1:3,], aes(x = model, y = wt*2000)) +
geom_col() +
scale_y_continuous(labels = function(y) comma(y))
# Fail
ggplot(mtcars[1:3,], aes(x = model, y = wt*2000)) +
geom_col() +
scale_y_continuous(labels = ~comma(y))
回答1:
An option is to wrap within purrr::as_mapper
library(scales)
library(ggplot2)
library(purrr)
ggplot(mtcars[1:3,], aes(x = model, y = wt*2000)) +
geom_col() +
scale_y_continuous(labels = as_mapper(~ comma(.)))
Or use rlang::as_function(~ comma(.))
Or simply use comma
without any anonymous function call
ggplot(mtcars[1:3,], aes(x = model, y = wt*2000)) +
geom_col() +
scale_y_continuous(labels = comma)
来源:https://stackoverflow.com/questions/59432347/using-anonymous-function-within-scale-y-continuous