Adding a vertical line to plotly plot using plotlyProxyInvoke without resizing the plot

Viewed 266

I am trying to add a vertical line to an existing plotly plot using the addTraces method. I'd like to understand why the new vertical lines are added two units to the right of where the first trace lays.

Fixing this issue will probably solve my original problem (question title) which is avoiding the plot resizing/moving to the right upon adding the new trace.

Here's an example of what I'm trying to do :

library(shiny)
library(plotly)

ui <- bootstrapPage(
  plotlyOutput("plot")
)

myvec <- rnorm(100)

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

  values <- reactiveValues(idx=1)

  output$plot <- renderPlotly({
    plot_ly(type='scatter', mode='lines') %>%
    add_trace(y=myvec[1])
  })

  plotproxy <- plotlyProxy("plot", session)

  observe({

    plotproxy %>%
      plotlyProxyInvoke("extendTraces",
        list(y=list(list(myvec[values$idx]))),
        list(1))

    if(!values$idx%%10) {
      plotproxy %>% plotlyProxyInvoke("addTraces",
        list(x=c(values$idx, values$idx),  # + 2 would "fix it"
             y=c(0,myvec[values$idx]),
             type="line", showlegend=F))
    }

  })

  observe({
    invalidateLater(1000)
    isolate({
      values$idx <- min(values$idx + 1, length(myvec))
    })
  })

}

shinyApp(ui = ui, server = server)

In short, I'd like the x axis limits to update with extendTraces only, I'm just guessing the 2 units mismatch is the problem.

1 Answers

I've managed to solve the x-axis mismatch, however this didn't solve the autosize issue. The problem was I wasn't using the same type and mode. Now it works :

library(shiny)
library(plotly)

ui <- bootstrapPage(
  plotlyOutput("plot")
)

myvec <- rnorm(100)

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

  values <- reactiveValues(idx=1)

  output$plot <- renderPlotly({
    plot_ly(type='scatter', mode='lines') %>%  # Must match with vertical line
    add_trace(x=c(-1,0), y=myvec[1])  # use x values
  })

  plotproxy <- plotlyProxy("plot", session)

  observe({

    plotproxy %>%
      plotlyProxyInvoke("extendTraces",
        list(x=list(list(values$idx)),  # match x values
             y=list(list(myvec[values$idx]))),
        list(1))

    if(!values$idx%%10) {
      plotproxy %>% plotlyProxyInvoke("addTraces",
        list(x=c(values$idx, values$idx),  # x limits match
             y=c(0,myvec[values$idx]),
             type='scatter', mode='lines', showlegend=F))  # must match
    }

  })

  observe({
    invalidateLater(1000)
    isolate({
      values$idx <- min(values$idx + 1, length(myvec))
    })
  })

}

shinyApp(ui = ui, server = server)
Related