I have an interactively displayed text in shiny, that captures the click event from a plotly plot. If nothing is clicked, a default text is displayed, once a point is clicked, its corresponding values are displayed.
However, I also have a radio button to select what is pictured in the plot. The problem is, when I change the selected radio button, the interactively displayed text is not correct anymore, since the plot changes and this is not captured, as you can see in the simplified example below. Therefore, I would like for the event_data to be reset (and hence show the default text) whenever I select a different option in the radio button.
I know there are ways to create a separate 'reset' button (e.g. with shinyjs
package, see here), yet I wonder whether it is possible to somehow couple this reset functionality to the radio button.
library(ggplot2)
library(shiny)
library(shinydashboard)
library(plotly)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
fluidRow(
box(plotlyOutput("first"),
radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
"petal"))
),
box(textOutput("second"))
)
)
)
server <- function(input, output, session) {
output$first <- renderPlotly({
if (input$radbut == "sepal") {
gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point()
} else {
gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
geom_point()
}
ggplotly(gp, source = "select")
})
output$second <- renderText({
clicked <- event_data("plotly_click", source = "select")
if (is.null(clicked)) {
text = "Select a value"
} else {
text = paste("You clicked:", input$radbut,
clicked[[3]],",", clicked[[4]], sep = " ")
}
text
})
}
shinyApp(ui, server)