Update plotly in R without recreating widget when plotted data is altered

戏子无情 提交于 2019-12-05 15:45:41

Take a look at these resources that might be useful to your case:

  1. Plotly R book by Carson Sievert chapters 3, 4 & 6
  2. Plotly proxy function explanation

This is the code to get you started. You have a bit of work to adjust the axis labels but this should not be that difficult.

Hope this helps!

The code:

    library("shiny")
    library("plotly")

    ui <- fluidPage(
            selectInput("dataset", "Choose a dataset:", choices = c("rock", "mtcars")),

            plotlyOutput("Plot1")
    )


    server <- function(input, output, session) {

            dataSource <- reactive({switch(input$dataset,"rock" = rock,"mtcars" = mtcars)})

            output$Plot1 <-  renderPlotly({plot_ly(data = rock, x = ~area, 
                                                   y =~peri, mode = 'markers', type = 'scatter')})

            observeEvent(input$dataset, {
                    f <- list(
                            family = "Courier New, monospace",
                            size = 18,
                            color = "#7f7f7f"
                    )
                    x <- list(
                            title = "x Axis",
                            titlefont = f, 
                            range = c(0, 1000)
                    )
                    y <- list(
                            title = "y Axis",
                            titlefont = f,
                            range = c(0, 100)
                    )
                    plotlyProxy("Plot1", session) %>%
                            plotlyProxyInvoke("addTraces", list(x = dataSource()[,1], 
                                                                y = dataSource()[,2],
                                                                type = 'scatter',
                                                                mode = 'markers')) %>% 
                            plotlyProxyInvoke("deleteTraces", list(as.integer(0))) %>% 
                            plotlyProxyInvoke("relayout", list(xaxis = x, yaxis = y))
            })



    }

    shinyApp(ui, server)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!