【问题标题】:ggplotly get data values of clicksggplotly 获取点击的数据值
【发布时间】:2021-03-30 07:27:09
【问题描述】:

如何获取使用 ggplot 创建的交互式地图的 x 和 y 坐标,并在 R Shiny 中绘制?我想获取 x 轴值并基于该显示其他数据。这是一些虚拟代码。

library(shiny)
library(plotly)
library(ggplot2)


ui <- fluidPage(

       plotlyOutput("distPlot")
    
 )


server <- function(input, output) {

output$distPlot <- renderPlotly({
    gg1 = iris %>% ggplot(aes(x = Petal.Length, y = Petal.Width)) + geom_point()
    ggplotly(gg1)
    })
}

 shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny r-plotly


    【解决方案1】:

    也许这就是您正在寻找的。 plotly 包提供了一个函数event_data() 来获取例如闪亮应用内点击事件的坐标。见here。如果您有多个绘图,您可以使用 source 参数来设置 id 并获取特定绘图的事件数据:

    library(shiny)
    library(plotly)
    library(ggplot2)
    
    
    ui <- fluidPage(
      
      plotlyOutput("distPlot"),
      verbatimTextOutput("info")
      
    )
    
    
    server <- function(input, output) {
      
      output$distPlot <- renderPlotly({
        gg1 = iris %>% ggplot(aes(x = Petal.Length, y = Petal.Width)) + geom_point()
        ggplotly(gg1, source = "Plot1")
      })
      
      output$info <- renderPrint({
        d <- event_data("plotly_click", source = "Plot1")
        
        if (is.null(d)) {
          "Click events appear here (double-click to clear)"
        } else {
          x <- round(d$x, 2)
          y <- round(d$y, 2)
          cat("[", x, ", ", y, "]", sep = "")
        }
      })
    }
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

    • 当我有多个情节时,我如何提供一些 id 以便引用点击的那个?
    • 您可以通过plot_lyggplotly 中的source 参数设置ID,并通过event_datasource 参数调用特定情节的事件。查看我的编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2022-09-30
    • 2022-10-14
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多