cpsievert / plotly_book

plotly for R book
https://plotly-r.com
Other
182 stars 124 forks source link

Section on restoring state from a bookmark? #45

Open cpsievert opened 5 years ago

cpsievert commented 5 years ago

Sort of like this example, which currently requires https://github.com/ropensci/plotly/pull/1392

library(shiny)
library(plotly)

ui <- function(req) {
  fluidPage(
    bookmarkButton(),
    plotlyOutput("plot")
  )
}

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

  output$plot <- renderPlotly({
    plot_ly(economics, x = ~pop, source = "pop_hist")
  })

  onRestored(function(state) {
    hist_relayout <- jsonlite::parse_json(
      state$input[["plotly_relayout-pop_hist-input"]]
    )
    xrng <- as.numeric(hist_relayout[c("xaxis.range[0]", "xaxis.range[1]")])

    if (length(xrng)) {
      plotlyProxy("plot") %>% 
        plotlyProxyInvoke("relayout", list(xaxis = list(range = xrng)))
    }
  })
}

shinyApp(ui, server, enableBookmarking = "url")
cpsievert commented 5 years ago

It's worth noting the example above could maybe handled automatically by plotly someday (seems like any restyle/relayout could be handled), so it's probably not a good idea to put in the book, but it might be worth demonstrating bookmarking with a 'side-effecty' example like persistent brushing with accumulating data.