Add plotly traces dynamically on shiny

后端 未结 1 1349
清酒与你
清酒与你 2021-02-09 20:30

I am building an app that allows a user to dynamically add and remove traces on a plotly graph using selectInput.

I have tried to play around with plotlyProxy () and plo

相关标签:
1条回答
  • 2021-02-09 20:50

    Here is a solution avoiding plotlyProxy() by filtering your data.frame before passing it to plot_ly:

    library(shiny)
    library(shinydashboard)
    library(plotly)
    
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(
        sidebarMenu(
          menuItem("Search", tabName = "Tabs", icon = icon("object-ungroup"))
    
        )
      ),
      dashboardBody(
        tabItem(tabName = "Tabs",
                fluidRow(
                  column(width=3, 
                         box(
                           title="SELECT ",
                           solidHeader=TRUE,
                           collapsible=TRUE,
                           width=NULL,
                           selectizeInput(
                             inputId="Player",
                             selected = NULL, multiple = TRUE,
                             label=" Choose Player", 
                             choices=c("Messi", "Suarez", "Ronaldo" ), options = list('plugins' = list('remove_button')))
                         )
                  ),
    
                  column( width=9,
                          tabBox(
                            width="100%",
                            tabPanel("tab1", 
                                     plotlyOutput("Plot1")
                            )))))))
    
    server <- function(input, output, session) {
      output$Plot1 <-  renderPlotly({
    
        goals <- data.frame(Name = c("Messi", "Suarez", "Ronaldo", "Messi", "Suarez", "Ronaldo", "Messi", "Suarez", "Ronaldo" ), 
                            Number= c(47, 35, 40, 49, 32, 31, 51, 49, 44 ),
                            Year = c("2018","2018","2018", "2017", "2017", "2017", "2016","2016","2016")
        )  
    
        filteredGoals <- reactive({
          goals[goals$Name %in% input$Player, ]
        })
    
        plot_ly(filteredGoals(), x = ~Year, y = ~Number, type = 'scatter', mode = 'lines', color = ~Name)%>% layout(showlegend = TRUE) %>%
          layout(title = 'Number of goals')
      })
    }
    shinyApp(ui, server)
    
    0 讨论(0)
提交回复
热议问题