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
xvarfrom coordinfo

Any suggestions would be appreciated?
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:

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