【问题标题】:Iterating with custom plotting functions using `map` family使用 `map` 系列使用自定义绘图函数进行迭代
【发布时间】:2020-02-06 04:37:34
【问题描述】:

我创建了一个自定义函数,可以使用ggplot2 包绘制直方图。我想遍历数据框的每一列,为每一列生成一个直方图。

library(tidyverse)

#Making function to facilitate variable iteration. Supply data frame and single variable name
histogram_fun = function(df = model_data, x = "variable_name") {
     ggplot(df, aes(x = .data[[x]] )) +
         geom_histogram() + 
         labs(x = x)
}

当我尝试histogram_fun(gss_cat, "age") 时,我得到了预期的直方图。但是,如果我想遍历变量 yearagetvhours,我会尝试这样的方法,但无济于事:

gss_numeric <- gss_cat %>% select_if(is.numeric) %>% names
gss_numeric
#> [1] "year"    "age"     "tvhours"

gss_cat %>% select(gss_numeric) %>% map(histogram_fun(df = ., x = gss_numeric))
#> Can't convert a `gg/ggplot` object to function

如何使用mapwalk 函数正确地迭代我的选择?

reprex package (v0.3.0) 于 2019 年 10 月 8 日创建

【问题讨论】:

    标签: r ggplot2 dplyr purrr


    【解决方案1】:

    这是我们将字符串转换为symbol 并评估 (!!) 的一种选择

    library(dplyr)
    library(purrr)
    library(ggplot2)
    histogram_fun <- function(data, x ) {
      ggplot(data, aes(!! rlang::sym(x) )) +
         geom_histogram() + 
         labs(x = x)
    }
    
    gss_numeric <- c("mpg", "disp")
    p1 <- map(gss_numeric, ~ histogram_fun(mtcars, .x))
    library(ggpubr)
    p1 <- map(gss_numeric, ~ histogram_fun(mtcars, .x))
    ggarrange(p1[[1]], p1[[2]], ncol = 2)
    

    【讨论】:

    • 感谢您提供ggpubr::ggarrange 代码。
    猜你喜欢
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2021-05-22
    • 2019-11-06
    • 1970-01-01
    • 2020-12-08
    • 2018-07-01
    相关资源
    最近更新 更多