3

我有一个有两个情节的闪亮应用程序。如果用户单击顶部图中的一个点,该点的 x 和 y 坐标将保存到一个响应式 Shiny 变量(在下面的代码中,它称为 pointSel)。

在底部图中,我希望将此 pointSel 的 x 和 y 坐标绘制为绿点。我目前有这个工作(如下面的脚本所示)。但是,每次更新 pointSel 对象时,都会重新绘制第二个图。相反,我试图保持第二个绘图背景不被绘制,并简单地在它上面覆盖一个新的绿点。

我相信这需要两件事:

1)onRender()函数中应用于“data = pointSel()”的isolate()函数。

2) 如果 pointSel 已更新,一些语法会提醒仅添加绿点跟踪。我在注释“$('#pointSel').on('click',function()”中给出了暂定语法。

下面是我的代码:

library(plotly)
library(GGally)
library(hexbin)
library(htmlwidgets)
library(tidyr)
library(shiny)
library(edgeR)
library(EDASeq)
library(dplyr)
library(data.table)
library(ggplot2)

ui <- shinyUI(fluidPage(
  plotlyOutput("plot1"),
  plotlyOutput("plot2")
))

server <- shinyServer(function(input, output) {

  data <- data.frame(mpg=mtcars$mpg,qsec=mtcars$qsec)

  output$plot1 <- renderPlotly({

    p <- qplot(data$mpg,data$qsec)
    pP <- ggplotly(p)

    pP %>% onRender("
      function(el, x, data) {

      el.on('plotly_click', function(e) {
        var pointSel = [e.points[0].x, e.points[0].y]
        Shiny.onInputChange('pointSel', pointSel);
      })}

      ", data = data)
  })

  pointSel <- reactive(input$pointSel)

  output$plot2 <- renderPlotly({

    p2 <- qplot(mpg,qsec,data=data, geom="point", alpha=I(0))
    pP2 <- ggplotly(p2)

    pP2 %>% onRender("
      function(el, x, data) {
        console.log('Whole bottom plot is being redrawn')
        var myX = data[0]
        var myY = data[1]
      //$('#pointSel').on('click',function() {
        var Traces = [];
        var trace = {
          x: [myX],
          y: [myY],
          mode: 'markers',
          marker: {
            color: 'green',
            size: 10
          }
        };
        Traces.push(trace);
        Plotly.addTraces(el.id, Traces);
      //})
    }", data = pointSel())
  })
})

shinyApp(ui, server)

注意:这与我之前发布的问题类似,并且有一个有用的答案(htmlWidgets 的 onRender() 函数中的 Shiny actionButton() 输出)。我遇到了这个问题的变体(无法将绘图的各个方面覆盖到 onRender() 函数中的背景图),而当前的帖子只是该问题的另一个变体。我正在尝试为这种情况找到类似的答案!谢谢你的任何建议。

4

1 回答 1

3

您可以在onRender函数中使用定义自定义消息处理程序并使用它server.R来传递选定的点坐标。

第二个图的onRender功能可能如下所示:

function(el, x, data) {
  Shiny.addCustomMessageHandler('draw_point',
  function(point) {
    var Traces = [];
    var trace = {
      x: [point[0]],
      y: [point[1]],
      mode: 'markers',
      marker: {
        color: 'green',
        size: 10
      }
    };
    Traces.push(trace);
    console.log(Traces);
    Plotly.addTraces(el.id, Traces);
  });
}

在你的server.R你可以这样做:

  observe({
    session$sendCustomMessage(type = "draw_point", input$pointSel)
  })

Whenever a point is selected, the coordinates will be sent to the function defined in the onRenderand the point will be drawn.

于 2017-05-02T11:47:14.743 回答