代码之家  ›  专栏  ›  技术社区  ›  ozgeneral

基于缩放的交互式绘图中y轴的重缩放

  •  0
  • ozgeneral  · 技术社区  · 6 年前

    我在rshiny上有一个交互式绘图,我希望根据用户缩放的位置动态缩放轴。我想我可以用 scale_y_continuous 不过,对于使用ylim动态元素的情况,我需要知道用户当前帧(已缩放的位置)的上下y值。有没有办法用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)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   AndS.    6 年前

    试试这个。它不是用阴谋,而是用同样的总体思路。实际上,它将数据过滤到画笔。双击将完全返回。

    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)
    

    reprex package (第0.2.0版)。

    推荐文章