ggplot方面包装变量作为函数中的参数 [英] ggplot facet wrap variable as an argument in a function
本文介绍了ggplot方面包装变量作为函数中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数,其中参数之一是分面换行的变量.
I'm trying to write a function where one of the arguments is the variable by which to facet wrap.
最小可重现的示例:
library(tidyverse)
library(ggplot2)
wobble<- matrix(1:9, 3) %>% as_tibble()
wibble_fun <- function(df, var) {
df %>%
ggplot(aes(var)) +
geom_bar() +
facet_wrap(~var)
}
wibble_fun(wobble, "V1")
产生的错误:
Error: At least one layer must contain all faceting variables: `var`.
* Plot is missing `var`
* Layer 1 is missing `
似乎像 facet_wrap(〜var)
中的 var
一样,它被解释为字符串"var",而不是被"V1"代替,这是我使用的第二个参数调用函数.
Seems like var
in facet_wrap(~var)
is interpreted as the string 'var' instead of being substituted by "V1", which is the second argument when I call the function.
有没有办法使这项工作成功?
Is there a way to make this work?
推荐答案
这是在函数内的变量周围使用 {{......}}
而不是使用 sym 代码>并取消报价:
Here's a solution using {{...}}
around the variable within the function instead of using sym
and unqoting:
library(tidyverse)
library(ggplot2)
wobble<- matrix(1:9, 3) %>% as_tibble()
wibble_fun <- function(df, var) {
df %>%
ggplot(aes({{var}})) +
geom_bar() +
facet_wrap(vars({{var}}))
}
wibble_fun(wobble, V1)
这篇关于ggplot方面包装变量作为函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文