Reputation: 27
I've a shiny app in which a custom function perform data manipulation and returns a combination of data frames and a plotly graph. However, let me create a example using mtcars which will illustrate the problem.
Custom function returning a list which has a plotly object and one other variable.
get_plot <- function(x_var)
{
p <- plot_ly() %>%
add_lines(data = mtcars, x = ~x_var, y = ~mpg, mode = "lines", line = list(width = 2), name = "Original") %>% layout(hovermode = 'compare') %>%
layout( xaxis = list(title = print('x_var'), gridcolor = "#bfbfbf", domain = c(0, 0.98)),
yaxis = list(title = "MPG", gridcolor = "#bfbfbf"))
p <- plotly_build(p)
a <- 1+1
return(list(p,a))
}
Shiny Code:
source("get_plot.R")
library(shiny)
ui <- fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
selectInput("x_var",
"Select X Axis variable",
c("hp","dist","drat","wt","disp","qsec","mpg"))
),
mainPanel(
plotlyOutput("distPlot")
)
)
)
server <- function(input, output) {
output$distPlot <- renderPlotly({
get_plot(input$x_var)[1]
})
}
# Run the application
shinyApp(ui = ui, server = server)
If you run this app, you will get the following error:
Error: no applicable method for 'ggplotly' applied to an object of class "list"
I understand what this means but I would like to ask whether there is a way to return a plotly object as part of a list in any other way. In my original shiny app the custom function does a lot of data processing after which it returns those data frames and the plotly object in a list. I am not able to access it and for now am getting around by making a copy of the same function and having it return just the plotly object. Not the most efficient obviously.
Thanks!
Upvotes: 1
Views: 677
Reputation: 25415
I think all you have to do is to use double brackets, since you are indexing a list:
output$distPlot <- renderPlotly({
get_plot(input$x_var)[[1]]
})
Hope this helps!
Upvotes: 3