rplotlycrosstalk

Passing variable name to user-defined function that makes a plotly chart


I'm having trouble with passing a variable name from a shared data set to a function I've defined.

I've seen documentation for similar R issues and have tried to implement some of the solutions to no avail.

In the reprex below, I encounter an error stating "Error in eval(expr, data, expr_env) : object 'pct_increase' not found"

Does anyone have a solution for this? Many thanks.

reprex:

library(tidyverse)
library(plotly)
library(crosstalk)

bar_tibble <- tibble(category = c("Cat 1", "Cat 1", "Cat 2", "Cat 2"),
                     pct_increase = c(0.17, 0.25, 0.64, 0.85),
                     week = c(1, 2, 1, 2)) 

bar_data_shared <- SharedData$new(bar_tibble, ~week)

SharedData$origData(bar_tibble)

make_bar_chart <- function(shared_data, xvar, yvar){
  
plot_ly(data = shared_data, hoverinfo = "none") %>%

  add_trace(
    x = ~xvar,
    y = ~yvar,
    type = "bar",
    transforms = list(
      list(
        type = "aggregate",
        groups = ~yvar,
        aggregations = list(
          list(
            target = "x", func = "avg", enabled = T)))))
}

make_bar_chart(bar_data_shared, pct_increase, category)

Solution

  • When you call your function, you have to use real objects or strings. In other words, you have to pass the column names as strings.

    From there you run into another issue. Once you make the column names strings Plotly will not connect columns to the SharedData object without additional intervention.

    Since I don't think you want the parameter name as the axes' labels, I added labels, as well.

    Here is what you can do to make this work.

    make_bar_chart <- function(shared_data, xvar, yvar){
      plot_ly(data = shared_data,
              hoverinfo = "none") %>%
        add_trace(
          x = ~.data[[xvar]],  # <- tell plotly 'connect to the data object!'
          y = ~.data[[yvar]],  # <- here, too
          type = "bar",
          transforms = list(
            list(
              type = "aggregate",
              groups = ~.data[[yvar]],  # <- here, too
              aggregations = list(
                list(
                  target = "x", func = "avg", enabled = T))))
          ) %>% 
        layout(xaxis = list(title = xvar),
               yaxis = list(title = yvar))
    }
    # pass non-environment variables as strings
    make_bar_chart(bar_data_shared, "pct_increase", "category")
    

    enter image description here