【问题标题】:Pass variables as parameters to plot_ly function将变量作为参数传递给 plot_ly 函数
【发布时间】:2017-12-11 19:39:35
【问题描述】:

我想创建一个函数,根据传入的参数创建不同类型的绘图。如果我创建以下数据

library(plotly)
#### test data
lead <- rep("Fred Smith", 30)
lead <- append(lead, rep("Terry Jones", 30))
lead <- append(lead, rep("Henry Sarduci", 30))
proj_date <- seq(as.Date('2017-11-01'), as.Date('2017-11-30'), by = 'day')
proj_date <- append(proj_date, rep(proj_date, 2))
set.seed(1237)
actHrs <- runif(90, 1, 100)
cummActHrs <- cumsum(actHrs)
forHrs <- runif(90, 1, 100)
cummForHrs <- cumsum(forHrs)
df <- data.frame(Lead = lead, date_seq = proj_date,
                 cActHrs = cummActHrs,
                 cForHrs = cummForHrs)

我可以使用:

plot_ly(data = df, x = ~date_seq, y = ~cActHrs, split = ~Lead)

如果我制作了如下所示的 ma​​kePlot 函数,我将如何让它做这样的事情:

makePlot <- function(plot_data = df, x_var = date_seq, y_var, split_var) {
    plot <- plot_ly(data = df, x = ~x_var, y = ~y_var, split = ~split_var)

    return(plot)
}

?

是否有一个函数可以包装 x_var、y_var 和 split_var,以便 plotly 将它们识别为 x、y 和 split 参数?

【问题讨论】:

    标签: r plotly


    【解决方案1】:

    最终解决了这个问题,并希望这个小小的后续行动能够解开这些类型任务的一些奥秘。尽管这个问题的重点是绘图,但重要的是首先要了解各种 R 包(例如 dplyr 和 plotly)中的函数如何评估表达式以及如何操作这些表达式的评估方式。建立这种理解的一个很好的参考是 Hadley 在 dplyr herehere 中编程的文章。

    一旦掌握了这些,这将变得非常容易。诀窍是像调用 dplyr 函数时一样简单地传递变量参数,并确保在绘图函数中引用这些参数。对于上面的问题,这个功能对我有用:

    makePlot <- function(plot_data = df, x_var, y_var, split_var,
                         type_var="scatter",
                         mode_var="lines+markers") {
        quo_x <- enquo(x_var)
        quo_y <- enquo(y_var)
        quo_split <- enquo(split_var)
        
        # print(c(quo_x, quo_y, quo_split))
        
        plot <- plot_ly(data = plot_data, x = quo_x, y = quo_y, split = quo_split,
                        type=type_var, mode=mode_var)
    
        return(plot)
    }
    
    # using df created in question, pass col's as args like dplyr functions
    p1 <- makePlot2(df, date_seq, cActHrs, Lead)
    p2 <- makePlot2(df, date_seq, cForHrs, Lead)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多