using anonymous function within scale_y_continuous

给你一囗甜甜゛ 提交于 2021-01-27 17:02:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!