如何在函数中传递 facet_grid() 的参数?

huangapple go评论94阅读模式
英文:

How to pass parameters of facet_grid() in a function?

问题

以下是您提供的代码的翻译部分:

让我们假设我有以下数据集。

    library(ggplot2)    
    test_data <- rnorm(40, 4, 3)
    factory <- sample(c("A", "B", "C"), 40, replace = TRUE)
    df <- data.frame(test_data, factory)

并且我有一个创建图表的函数,如下所示:

    graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
      graph <- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})), y={{y_axis_parameter}},
        colour= {{category}})) +
        geom_line() +
        geom_point() +
        facet_grid(.~{{category}}) +
        ylab(paste0(attribute_name, " Measured Values")) +
        xlab("Data Points") +
        labs(title = paste0(attribute_name)) +
        theme(legend.position = "none") 
    
      graph
    }
    
    graph_builder(df, test_data, category, "Test graph")

这段代码的所有行都能正常工作,除了 facet_grid()。我假设将列名传递给双大括号{{}}会起作用。然而,似乎 facet_grid() 不支持以这种方式传递列名。

我该如何解决这个问题?
英文:

Lets say I have the following dataset.

library(ggplot2)    
test_data &lt;- rnorm(40, 4, 3)
factory &lt;- sample(c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), 40, replace = TRUE)
df &lt;- data.frame(test_data, factory)

And I have a function that creates a graph such as following:

graph_builder &lt;- function(data_set, y_axis_parameter, category, attribute_name) {
  graph &lt;- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})), y={{y_axis_parameter}},
    colour= {{category}})) +
    geom_line() +
    geom_point() +
    facet_grid(.~{{category}}) +
    ylab(paste0(attribute_name, &quot; Measured Values&quot;)) +
    xlab(&quot;Data Points&quot;) +
    labs(title = paste0(attribute_name)) +
    theme(legend.position = &quot;none&quot;) 

  graph
}

graph_builder(df, test_data, category, &quot;Test graph&quot; )

This code functions correctly in all lines except for facet_grid(). I assumed that passing the column name in double curly braces {{}} would work. However, it appears that facet_grid() does not support passing the column name in this manner.

How can I resolve this issue?

答案1

得分: 2

我建议传递一个原始变量名称,比如 factory,然后将其放在大括号中传递给 facet_gridrows 和/或 cols 参数:

graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
    graph <- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})), y={{y_axis_parameter}},
                                  colour= {{category}})) +
      geom_line() +
      geom_point() +
      facet_grid(rows = vars({{category}})) +
      ylab(paste0(attribute_name, " Measured Values")) +
      xlab("Data Points") +
      labs(title = paste0(attribute_name)) +
      theme(legend.position = "none") 
    
    graph
  }

graph_builder(df, test_data, factory, "Test graph" )

[![enter image description here][1]][1]


<details>
<summary>英文:</summary>

I&#39;d recommend passing a raw variable name like `factory`, and feeding that in curly braces to the `rows` and/or `cols` parameters of `facet_grid`:

    graph_builder &lt;- function(data_set, y_axis_parameter, category, attribute_name) {
        graph &lt;- ggplot(data_set, aes(x=seq(length({{y_axis_parameter}})), y={{y_axis_parameter}},
                                      colour= {{category}})) +
          geom_line() +
          geom_point() +
          facet_grid(rows = vars({{category}})) +
          ylab(paste0(attribute_name, &quot; Measured Values&quot;)) +
          xlab(&quot;Data Points&quot;) +
          labs(title = paste0(attribute_name)) +
          theme(legend.position = &quot;none&quot;) 
        
        graph
      }
    
    graph_builder(df, test_data, factory, &quot;Test graph&quot; )

   [![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/ckPoD.png

</details>



# 答案2
**得分**: 0

在R中,`rlang`包的`sym()`函数可用于将字符串转换为符号。然后,我们可以使用`!!`运算符来取消引用该符号。这使我们能够以编程方式将变量传递给ggplot美学或其他通常不将字符串作为变量名进行评估的参数。在这种情况下,我们可以使用这种方法基于变量列名称创建`facet_grid`。

```R
library(ggplot2)
library(rlang)

graph_builder <- function(data_set, y_axis_parameter, category, attribute_name) {
  y_var <- enquo(y_axis_parameter)
  category_var <- sym(category)
  
  graph <- ggplot(data_set, aes(x = seq_along(!!y_var), y = !!y_var, colour = !!category_var)) +
    geom_line() +
    geom_point() +
    facet_grid(. ~ !!category_var) +
    ylab(paste0(attribute_name, " Measured Values")) +
    xlab("Data Points") +
    labs(title = paste0(attribute_name)) +
    theme(legend.position = "none") 

  graph
}

graph_builder(df, test_data, "factory", "Test graph")

在上述函数中,enquo()用于引用y_axis_parameter,以便在整洁评估环境中使用(通过!!运算符)。sym()函数用于将类别参数转换为符号,以便可以使用!!取消引用并在facet_grid()内进行评估。

英文:

In R, the rlang package's sym() function can be used to convert a string into a symbol. We can then use the !! operator to unquote the symbol. This allows us to programmatically pass variables to ggplot aesthetics or other arguments which typically do not evaluate strings as variable names. In this case, we can use this method to create a facet_grid based on a variable column name.

library(ggplot2)
library(rlang)

graph_builder &lt;- function(data_set, y_axis_parameter, category, attribute_name) {
  y_var &lt;- enquo(y_axis_parameter)
  category_var &lt;- sym(category)
  
  graph &lt;- ggplot(data_set, aes(x = seq_along(!!y_var), y = !!y_var, colour = !!category_var)) +
    geom_line() +
    geom_point() +
    facet_grid(. ~ !!category_var) +
    ylab(paste0(attribute_name, &quot; Measured Values&quot;)) +
    xlab(&quot;Data Points&quot;) +
    labs(title = paste0(attribute_name)) +
    theme(legend.position = &quot;none&quot;) 

  graph
}

graph_builder(df, test_data, &quot;factory&quot;, &quot;Test graph&quot;)

In the function above enquo() is used to quote the y_axis_parameter so it can be used in a tidy evaluation context (via the !! operator). The sym() function is used to convert the category argument to a symbol, so it can be unquoted with !! and evaluated within facet_grid().

huangapple
  • 本文由 发表于 2023年8月5日 05:23:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定