Search code examples
rr-plotly

How to return a plotly figure from a function?


Beginner here so please be gentle! ;)

I am using plotly in R to generate some figures.

The code works fine when it is run directly in a script, but fails when I try to output a plotly figure from a function.

For example, typing the following in and running directly displays the figure and works fine (data is a list containing lots of different parameters):

fig1 <- plot_ly(x = 0:100, y = data[[parameter]], type = 'scatter', mode = 'lines', line = list(color = 'rgba(191,191,191,0.2)'))
fig1

I have a lot of plots to do, so have made the following function:

Special_plot <- function(data, parameter){fig1 <- plot_ly(x = 0:100, y = data[[parameter]], type = 'scatter', mode = 'lines', line = list(color = 'rgba(191,191,191,0.2)'))
    return(fig1)
}

The function runs, but when it comes to displaying the figure I get an error message:

fig1 <- Special_plot(data, parameter) 
fig1

This is the error message:

Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 0: Column `y`
* Length 101: Column `x`
Run `rlang::last_error()` to see where the error occurred.

I have a lot of figures to process and would like to avoid typing each one individually. Any help massively appreciated!


Solution

  • I think your x is going off limits. Maybe try and change the x variable like below. Also the 0 index is not present in R. So you have to start with 1.

     Special_plot <- function(data, parameter){ fig1 <- plot_ly(x = 1:length(data[[parameter]]), y = data[[parameter]], type = 'scatter', mode = 'lines', line = list(color = 'rgba(191,191,191,0.2)'))
            return(fig1)
        }
    
    fig1 <- Special_plot(data, parameter) 
    fig1