在函数内将字符串传递给 ggplot2 [英] pass character strings to ggplot2 within a function

查看:16
本文介绍了在函数内将字符串传递给 ggplot2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在工作中使用

其他几种选择 -

#使用获取乐趣 <- 函数(数据,x,y){ggplot(dat, aes(x = get(x), y = get(y))) +geom_point()}#使用符号乐趣 <- 函数(数据,x,y){ggplot(dat, aes(x = !!sym(x), y = !!sym(y))) +geom_point()}

Often I use ggplot2 in my work and build wrapper functions to speed up my work flow. The use of the non-standard evaluation (NSE) aes forces me to use the actual variable names rather than passing character strings. So I copy and rename dataframes and variable names to appease ggplot2. There's got to be a better way. How can I make ggplot2 accept unknown dataframes and column names via a function wrapper without replicating the dataframe and using generic column names?

This works:

ggplot(mtcars, aes(x=mpg, y=hp)) +
    geom_point()

This does not:

FUN <- function(dat, x, y) {
    ggplot(dat, aes(x = x, y = y)) +
        geom_point()
}

FUN(mtcars, "mpg", "hp")

解决方案

It is now recommended to use .data pronoun

FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = .data[[x]], y = .data[[y]])) +
    geom_point()
}

FUN(mtcars, "mpg", "hp")

Couple of other alternatives -

#Using get
FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = get(x), y = get(y))) +
    geom_point()
}

#Using sym

FUN <- function(dat, x, y) {
  ggplot(dat, aes(x = !!sym(x), y = !!sym(y))) +
    geom_point()
}

这篇关于在函数内将字符串传递给 ggplot2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆