Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables as parameters to plot_ly function

Tags:

r

plotly

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?

like image 557
Michael Szczepaniak Avatar asked Dec 11 '17 19:12

Michael Szczepaniak


1 Answers

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 = 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)
like image 162
Michael Szczepaniak Avatar answered Oct 26 '22 00:10

Michael Szczepaniak