File: app.R

package info (click to toggle)
r-cran-plotly 4.10.4%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 30,636 kB
  • sloc: javascript: 195,272; sh: 24; makefile: 6
file content (45 lines) | stat: -rw-r--r-- 1,317 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
library(shiny)
library(plotly)

ui <- fluidPage(
  plotlyOutput("plot")
)

server <- function(input, output, session) {
  
  p <- ggplot(txhousing) +
    geom_line(aes(date, median, group = city))
  
  output$plot <- renderPlotly({
    ggplotly(p, dynamicTicks = TRUE) %>% 
      rangeslider() 
  })
  
  observeEvent(event_data("plotly_relayout"), {
    d <- event_data("plotly_relayout")
    # unfortunately, the data structure emitted is different depending on 
    # whether the relayout is triggered from the rangeslider or the plot
    xmin <- if (length(d[["xaxis.range[0]"]])) d[["xaxis.range[0]"]] else d[["xaxis.range"]][1]
    xmax <- if (length(d[["xaxis.range[1]"]])) d[["xaxis.range[1]"]] else d[["xaxis.range"]][2]
    if (is.null(xmin) || is.null(xmax)) return(NULL)
    
    # compute the y-range based on the new x-range
    idx <- with(txhousing, xmin <= date & date <= xmax)
    yrng <- extendrange(txhousing$median[idx])
    
    plotlyProxy("plot", session) %>%
      plotlyProxyInvoke("relayout", list(yaxis = list(range = yrng)))
  })
  
  yRange <- range(txhousing$median, na.rm = TRUE)
  observeEvent(event_data("plotly_doubleclick"), {
    
    plotlyProxy("plot", session) %>%
      plotlyProxyInvoke("relayout", list(yaxis = list(range = yRange)))
    
  })
  
  
}

shinyApp(ui, server)