2
votes

I want a pop-up when I click over the bar chart for plotly.

library(shiny)
library(shinymaterial)
df1 <- data.frame(x = 1:10, y = 1:10)
df2 <- data.frame(x = c(rep('a', 10), rep('b', 10)),
y = c(rnorm(10), rnorm(10, 3, 1)))
ui <- material_page(title = "Material Design",
  tags$br(),
  font_color = "cyan darken-5",
  nav_bar_color = "cyan darken-5",
  plotlyOutput('scatter')
)
server <- function(input, output) {
  output$scatter <- renderPlotly({
    plot_ly(df1, x = df1$x, y = df1$y, type = 'bar', source = 'scatter')
  })
}
shinyApp(ui = ui, server = server)

I am struck at a point where I need a help; I want a pop-up when I click over the bar chart the respective contents to be displayed. Please help me on the same.

1

1 Answers

2
votes

You can use an observer and the event_data from your scatterchart to accomplish that. Working example below, hope this helps!

library(shiny)
library(plotly)
df1 <- data.frame(x = 1:10, y = 1:10)
df2 <- data.frame(x = c(rep('a', 10), rep('b', 10)),
                  y = c(rnorm(10), rnorm(10, 3, 1)))
ui <- fluidPage(
                    plotlyOutput('scatter')
)
server <- function(input, output) {
  output$scatter <- renderPlotly({
    plot_ly(df1, x = df1$x, y = df1$y, type = 'bar', source = 'scatter')
  })

  observeEvent(event_data("plotly_click", source = "scatter"),
               {
                 event_data = event_data("plotly_click", source = "scatter")
                 showModal(modalDialog(
                   title = "Important message",
                   paste0('x: ', event_data$x, ', y: ', event_data$y)
                 ))
               }
               )
}
shinyApp(ui = ui, server = server)