Pass variables as parameters to plot_ly function

旧城冷巷雨未停 提交于 2019-12-13 15:21:29

问题


I would like to create a function that creates different kinds of plotly plots based on the parameters that are passed into it. If I create the following data

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)

I could plot it using:

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

If I made a makePlot function like the one shown below, how would I make it do something like this:

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)
}

?

Is there a function I can wrap x_var, y_var, and split_var with so that plotly will recognize them as x, y, and split parameters?


回答1:


Eventually got around to figuring this out and hope this little follow up takes some of the mystery of these types of tasks. Although this question is focused on plotting, it's important to first build an understanding of how the functions in various R packages (e.g. dplyr and plotly) evaluate expressions and how to manipulate the way those expressions are evaluated. A great reference to build this understanding is Hadley's article on programming in dplyr here or alternatively here.

Once that's under your belt, this turns out to be pretty easy. The trick is to simply pass your variable arguments like you do when you call dplyr functions and be sure to quote those parameters inside your plotting function. For the question above, this function worked for me:

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 = df, 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)


来源:https://stackoverflow.com/questions/47760169/pass-variables-as-parameters-to-plot-ly-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!