You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言Plotly中获取绘制矩形坐标并实现实时更新

在R语言Plotly中实时获取并更新绘制矩形的坐标

要实现绘制矩形时坐标同步到独立R变量,且调整矩形时自动更新,需要结合Plotly绘图、htmlwidgets的JS回调以及Shiny的交互事件传递(纯静态Plotly无法直接将前端事件同步到R环境)。

完整解决方案代码

library(plotly)
library(shiny)
library(htmlwidgets)

ui <- fluidPage(
  plotlyOutput("plot"),
  verbatimTextOutput("rect_coords") # 实时展示矩形坐标,用于验证
)

server <- function(input, output, session) {
  # 初始化存储矩形坐标的独立变量(reactiveVal支持实时更新)
  rect_data <- reactiveVal(list())
  
  # 生成示例数据
  x <- 1:50
  y <- rnorm(50)
  
  output$plot <- renderPlotly({
    plot_ly(x = ~x, y = ~y, type = 'scatter', mode = 'lines') %>%
      config(modeBarButtonsToAdd = list('drawrect')) %>%
      onRender("
        function(el, x) {
          // 监听矩形绘制完成事件
          el.on('plotly_clickannotation', function(e) {
            if(e.annotation.type === 'rect') {
              const rect = {
                x0: e.annotation.x0,
                x1: e.annotation.x1,
                y0: e.annotation.y0,
                y1: e.annotation.y1
              };
              // 将坐标传递给Shiny的input对象
              Shiny.setInputValue('rect_coords', rect);
            }
          });
          // 监听矩形调整(拖拽)事件
          el.on('plotly_relayout', function(e) {
            // 判断是否为矩形调整操作
            if(e['shapes[0].x0'] !== undefined) {
              const rect = {
                x0: e['shapes[0].x0'],
                x1: e['shapes[0].x1'],
                y0: e['shapes[0].y0'],
                y1: e['shapes[0].y1']
              };
              Shiny.setInputValue('rect_coords', rect);
            }
          });
        }
      ")
  })
  
  # 同步前端传递的坐标到R变量
  observeEvent(input$rect_coords, {
    rect_data(input$rect_coords)
  })
  
  # 输出当前矩形坐标,便于查看
  output$rect_coords <- renderPrint({
    cat("当前矩形坐标:\n")
    str(rect_data())
  })
}

shinyApp(ui, server)

关键说明

  • rect_data是存储矩形坐标的独立变量,通过reactiveVal实现实时更新,在server中可通过rect_data()随时调用最新坐标
  • 两个核心JS事件监听:
    • plotly_clickannotation:捕获矩形绘制完成的初始坐标
    • plotly_relayout:捕获矩形拖拽调整后的更新坐标
  • 通过Shiny.setInputValue将前端JS获取的坐标传递到R环境,再通过observeEvent同步到rect_data变量

使用方式

运行上述代码启动Shiny应用,使用工具栏的drawrect工具绘制矩形,拖拽调整大小时,下方文本框会实时显示最新坐标,rect_data()变量也会同步更新,可直接用于后续数据分析或操作。

内容的提问来源于stack exchange,提问作者mr.T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:23:13