Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nearPoints not able to automatically infer `xvar` from shiny coordinfo

I am trying to find the points in a ggplot near a mouse click using the nearPoints function, but it is not working. I used the code below to create shiny app with two plots for diamonds data.frame:

library(shiny)
library(ggplot2)
ui <- fluidPage(
mainPanel(
uiOutput("tb")
)
)
server <- function(input,output){

   output$diamonds1 <- renderPlot({

        print(ggplot(diamonds, aes(x=carat, y=price, col=clarity)) + 
                                geom_point(alpha=0.5)+ facet_wrap(~color, scales="free"))
   })
   output$diamonds2 <- renderPlot({

        print(ggplot(diamonds, aes(x=carat, y=price, col=clarity)) + 
                               geom_point(alpha=0.5)+ facet_wrap(~cut, scales="free"))
   }) 

   output$info <- renderPrint({

        nearPoints(diamonds, input$plot_click, threshold = 10, maxpoints = 1,
                   addDist = TRUE)
   })

output$tb <- renderUI({
tabsetPanel(tabPanel("First plot", 
                     plotOutput("diamonds1")),
            tabPanel("Second plot", 
                     plotOutput("diamonds2", click = "plot_click"), 
                     verbatimTextOutput("info"))) 
})
}
shinyApp(ui = ui, server = server) 

I keep getting this error in the second plot

Error: nearPoints: not able to automatically infer xvar from coordinfo

enter image description here

Any suggestions would be appreciated?

like image 703
shiny Avatar asked Jan 01 '26 05:01

shiny


1 Answers

This is what you want I think. You were "print"ing the ggplot, which apparently confuses nearPoints:

library(shiny)
library(ggplot2)
ui <- fluidPage(
  mainPanel(
    uiOutput("tb")
  )
)
server <- function(input,output){

  output$diamonds1 <- renderPlot({

    print(ggplot(diamonds, aes(x=carat, y=price, col=clarity)) + 
                            geom_point(alpha=0.5)+ facet_wrap(~color, scales="free"))
  })
  output$diamonds2 <- renderPlot({

    ggplot(diamonds, aes(x=carat, y=price, col=clarity)) + 
                     geom_point(alpha=0.5)+ facet_wrap(~cut, scales="free")
  }) 

  output$info <- renderPrint({
    nearPoints(diamonds,input$plot_click,threshold = 10, maxpoints = 1,addDist = TRUE)
  })

  output$tb <- renderUI({
    tabsetPanel(tabPanel("First plot", 
                         plotOutput("diamonds1")),
                tabPanel("Second plot", 
                         plotOutput("diamonds2", click = "plot_click"), 
                         verbatimTextOutput("info"))) 
  })
}
shinyApp(ui = ui, server = server) 

Yielding this - note the data.frame output is the points in diamonds that are near the mouse click:

enter image description here

like image 93
Mike Wise Avatar answered Jan 03 '26 19:01

Mike Wise



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!