Home > database >  selecting data by brush on shiny
selecting data by brush on shiny

Time:06-08

I have a reproducible shiny, I have tried to implement brushedPoints for the plot, however, I'm just getting errors. Is there any way to fix this so that when I click or select a point with the brush on the plot, the data connected to it, appears in a table? Thanks in advance

Error: brushedPoints: 'xvar' ('x') not in names of input

library(shiny)
library(plotly)

dataset <- mtcars

ui <- shinyUI(pageWithSidebar(
  headerPanel("Mtcars"),
  sidebarPanel(sliderInput('sampleSize', 'Sample Size', min=10, max=nrow(dataset),
                           value=min(10, nrow(dataset)), step=5, round=0),
               selectInput('x', 'X', names(dataset)),
               selectInput('y', 'Y', names(dataset), names(dataset)[[2]]),
               selectInput('color', 'Color', c('None', names(dataset))),
               checkboxInput('smooth', 'Smooth'),
               selectInput('facet_row', 'Facet Row', c(None='.', names(dataset))),
               selectInput('facet_col', 'Facet Column', c(None='.', names(dataset))),
               hr(),
               checkboxInput("plotly1", "Interactive plot!",value = FALSE, width=140),
               actionButton("plot", "Plot!")
  ),
  mainPanel(
    plotOutput('plot', click = "plot_click",
               hover = hoverOpts(id = "plot_hover", delayType = "throttle"),
               brush = brushOpts(id = "plot_brush")),
    tableOutput("plot_brushedpoints")

  )
))

server<- shinyServer(function(input, output) { 
  dataset <- reactive( { mtcars[sample(nrow(mtcars), input$sampleSize),] }) 
  gragh <- reactive({
    p <- ggplot(dataset(), aes_string(x=input$x, y=input$y))   geom_point()
    if (input$color != 'None')
      p <- p   aes_string(color=input$color)
    facets <- paste(input$facet_row, '~', input$facet_col)
    if (facets != '. ~ .')
      p <- p   facet_grid(facets)
    
    if (input$smooth)
      p <- p   geom_smooth()
    
    p
  }) |> bindEvent(input$plot)
  
  output$plot <- renderPlot({
    gragh()
  })
  
  output$plot_brushedpoints <- renderTable({
    df<- mtcars  
    res <- brushedPoints(df, input$plot_brush, "x", "y",allRows = TRUE)
    if (nrow(res) == 0|is.null(res))
      return(NULL)
    res
  })
  
  
  
  
})

CodePudding user response:

Not sure what you are trying to do with "x" and "y". Removing them makes it work:

res <- brushedPoints(df, input$plot_brush, allRows = TRUE)

You are putting "x" and "y" into xvar and yvar, but these need to be column names from your df.

brushedPoints(
  df,
  brush,
  xvar = NULL,
  yvar = NULL,
  panelvar1 = NULL,
  panelvar2 = NULL,
  allRows = FALSE
)


xvar, yvar
A string giving the name of the variable on the x or y axis. 
These are only required for base graphics, and must be the name of a column in df.
  • Related