显示模态onclick绘图条形图

时间:2019-08-06 06:06:58

标签: r shiny 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)

我在需要帮助的时候感到震惊;我想点击一个弹出窗口 在条形图上,要显示的相应内容。 请同样帮我。

1 个答案:

答案 0 :(得分:2)

您可以使用观察者和分散图中的event_data来完成此操作。下面的工作示例,希望对您有所帮助!

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)