0

I have an interactive plot on rshiny and I would like the axes to scale dynamically depending on where user zoomed. I think I can use scale_y_continuous for that using dynamic elements for ylim, however then I need to know the lower and upper y value of users current frame (where has been zoomed). Is there a way to achieve this with ggplot/rshiny?

require(shiny)
library(dplyr)
library(ggplot2)

ui <- fluidPage(
  titlePanel(title=h4("example", align="center")),
  mainPanel(plotlyOutput("plot"))
  )

##server
server <- function(input,output){
  dat<-reactive({
    num<-c(1,2,3,4,5,6,7,8,9)
    let<-c("A","B","C","D","E","F","G","H","I")
    df<-data.frame(num,let)
    df
  })

  output$plot<-renderPlotly({
    gg <- ggplot(dat(),aes(x=let,y=num))+geom_point(aes(colour='red'))
    gg2 <- ggplotly(gg) %>% layout(dragmode="select")
    gg2
  })
}

shinyApp(ui = ui, server = server)
ozgeneral
  • 6,079
  • 2
  • 30
  • 45

1 Answers1

3

Try this out. It doesn't use plotly, but same general idea. Essentially it filters the data to the brush. Double clicking will return to full extent.

require(shiny)
library(dplyr)
library(ggplot2)

ui <- fluidPage(
  titlePanel(title=h4("example", align="center")),
  mainPanel(
    plotOutput("plot", brush = brushOpts("brush_p")))
  )

##server
server <- function(input,output){
  dat<-reactive({
    num<-c(1,2,3,4,5,6,7,8,9)
    let<-c("A","B","C","D","E","F","G","H","I")
    df<-data.frame(num,let)
    df
  })

  dat2 <- reactive({
    y_max <- input$brush_p$ymax
    y_min <- input$brush_p$ymin
    if(is.null(y_max)) return(dat())
    dat() %>% filter(num > y_min & num < y_max)
  })

  output$plot<-renderPlot({
    gg <- ggplot(dat2(),aes(x=let,y=num))+geom_point(aes(colour='red'))
    gg
  })
}

shinyApp(ui = ui, server = server)

Created on 2018-08-19 by the reprex package (v0.2.0).

AndS.
  • 7,748
  • 2
  • 12
  • 17