Skip to contents

A Shiny app can add data to a plot already in the browser, instead of rendering it again: plotlyProxy() refers to the plot, and plotlyProxyInvoke() calls a plotly.js function on it. For streaming data, that function is extendTraces, which appends points to traces and can drop the oldest, so the plot shows a moving window. Only the new points are sent, and the rest of the plot is untouched: zoom, hidden traces and hover stay as they are.

The app

This app plots the sine and cosine of the time (seconds since 1970) for the last 60 seconds, adding a point to each trace ten times a second.

library(shiny)
library(plotly.core)

window <- 60 # seconds shown
rate <- 10 # points per second
n <- window * rate # points kept per trace

# Times as plotly.js date strings (local time, with milliseconds)
stamp <- function(t) format(t, "%Y-%m-%d %H:%M:%OS3")

ui <- fluidPage(plotlyOutput("stream"))

server <- function(input, output, session) {
  # Rendered once: the last 60 seconds, so the window starts full
  output$stream <- renderPlotly({
    t <- Sys.time() - seq(window, 0, length.out = n)
    go_figure() |>
      add_scatter(x = stamp(t), y = sin(as.numeric(t)), mode = "lines", name = "sin(t)") |>
      add_scatter(x = stamp(t), y = cos(as.numeric(t)), mode = "lines", name = "cos(t)") |>
      update_layout(yaxis_range = c(-1.1, 1.1))
  })

  proxy <- plotlyProxy("stream", session)

  # Ten times a second: one new point for each trace, keeping the last n
  observe({
    invalidateLater(1000 / rate)
    t <- Sys.time()
    s <- as.numeric(t)
    plotlyProxyInvoke(
      proxy,
      "extendTraces",
      list(x = list(I(stamp(t)), I(stamp(t))), y = list(I(sin(s)), I(cos(s)))),
      I(c(0L, 1L)),
      n
    )
  })
}

shinyApp(ui, server)

The arguments after "extendTraces" are those of Plotly.extendTraces(gd, update, indices, maxPoints):

Argument Here Meaning
update list(x = list(...), y = list(...)) For each attribute, a list with the new values of each trace
indices I(c(0L, 1L)) The traces to extend, counting from 0
maxPoints n (600) Points kept per trace: the oldest are dropped

I() keeps one-value vectors as arrays (["2026-11-17 12:00:00.100"]), which extendTraces needs: plain length-one vectors are sent as single values.

What it looks like

The plot below runs the same update in plain JavaScript, without Shiny, so you can see the result straight away: each trace keeps 600 points, the window moves, and zooming or hiding a trace isn’t undone by the updates.

Show the code: the same update in JavaScript
library(plotly.core)
fig <- go_figure() |>
  add_scatter(x = character(), y = numeric(), mode = "lines", name = "sin(t)") |>
  add_scatter(x = character(), y = numeric(), mode = "lines", name = "cos(t)") |>
  update_layout(height = 350, yaxis_range = c(-1.1, 1.1), xaxis_type = "date")
htmlwidgets::onRender(as_widget(fig), "
function(el) {
  var n = 600, step = 100;
  var pad = function(v, w) { return String(v).padStart(w || 2, '0'); };
  var stamp = function(d) {
    return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' +
      pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' +
      pad(d.getMilliseconds(), 3);
  };
  // fill the window with the last 60 seconds, then add a point every 100 ms
  var now = Date.now(), x = [], s = [], c = [];
  for (var i = n - 1; i >= 0; i--) {
    var t = now - i * step;
    x.push(stamp(new Date(t))); s.push(Math.sin(t / 1000)); c.push(Math.cos(t / 1000));
  }
  Plotly.extendTraces(el, {x: [x, x.slice()], y: [s, c]}, [0, 1], n);
  setInterval(function() {
    var t = Date.now(), d = stamp(new Date(t));
    Plotly.extendTraces(el, {x: [[d], [d]], y: [[Math.sin(t / 1000)], [Math.cos(t / 1000)]]}, [0, 1], n);
  }, step);
}")

A polar spiral

The same approach works for any trace type with arrays to extend. This app draws two spirals on a polar plot: the angle of each point is the time modulo 2π, in radians (thetaunit = "radians" on the traces; a turn takes 2π ≈ 6.3 seconds), the second spiral a quarter turn ahead, and the radius is the seconds since the session started. With rangemode = "normal" the radial axis covers just the last 60 seconds, so the newest points are at the edge and the spiral winds inwards to the oldest, about 9.5 turns.

library(shiny)
library(plotly.core)

window <- 60 # seconds shown
rate <- 10 # points per second
n <- window * rate # points kept per trace

ui <- fluidPage(plotlyOutput("spiral", height = "500px"))

server <- function(input, output, session) {
  t0 <- as.numeric(Sys.time()) - window # the radius counts seconds from here

  output$spiral <- renderPlotly({
    s <- seq(t0, t0 + window, length.out = n) # the last 60 seconds
    go_figure() |>
      add_scatterpolar(r = s - t0, theta = s %% (2 * pi), thetaunit = "radians",
                       mode = "lines", name = "t mod 2π") |>
      add_scatterpolar(r = s - t0, theta = (s + pi / 2) %% (2 * pi), thetaunit = "radians",
                       mode = "lines", name = "(t + π/2) mod 2π") |>
      update_layout(
        polar_angularaxis_thetaunit = "radians", # axis labels in radians too
        polar_radialaxis_rangemode = "normal" # not from 0: the last 60 seconds
      )
  })

  proxy <- plotlyProxy("spiral", session)

  observe({
    invalidateLater(1000 / rate)
    s <- as.numeric(Sys.time())
    plotlyProxyInvoke(
      proxy,
      "extendTraces",
      list(
        r = list(I(s - t0), I(s - t0)),
        theta = list(I(s %% (2 * pi)), I((s + pi / 2) %% (2 * pi)))
      ),
      I(c(0L, 1L)),
      n
    )
  })
}

shinyApp(ui, server)

In the browser:

Show the code: the same update in JavaScript
spiral <- go_figure() |>
  add_scatterpolar(r = numeric(), theta = numeric(), thetaunit = "radians", mode = "lines",
                   name = "t mod 2π") |>
  add_scatterpolar(r = numeric(), theta = numeric(), thetaunit = "radians", mode = "lines",
                   name = "(t + π/2) mod 2π") |>
  update_layout(height = 500, polar_angularaxis_thetaunit = "radians",
                polar_radialaxis_rangemode = "normal")
htmlwidgets::onRender(as_widget(spiral), "
function(el) {
  var n = 600, step = 100, t0 = Date.now() / 1000 - 60, tau = 2 * Math.PI;
  var mod = function(a) { return ((a % tau) + tau) % tau; };
  var r = [], a = [], b = [];
  for (var i = n - 1; i >= 0; i--) {
    var s = Date.now() / 1000 - i * step / 1000;
    r.push(s - t0); a.push(mod(s)); b.push(mod(s + Math.PI / 2));
  }
  Plotly.extendTraces(el, {r: [r, r.slice()], theta: [a, b]}, [0, 1], n);
  setInterval(function() {
    var s = Date.now() / 1000;
    Plotly.extendTraces(el, {r: [[s - t0], [s - t0]], theta: [[mod(s)], [mod(s + Math.PI / 2)]]}, [0, 1], n);
  }, step);
}")

A 3D path

3D traces (scatter3d) are drawn with WebGL, like scattergl, and are extended the same way. This app draws the path x = sin(t), y = cos(t), z = tan(t) for the last 5 seconds, with a marker at its tip. The two traces keep different numbers of points: maxPoints can give each attribute of each trace its own limit, here 50 points for the path and 1 for the marker.

tan(t) jumps from +∞ to −∞ each time t passes π/2 + kπ. A missing value (NA, sent as null) at each jump stops the path drawing a line across the plot there, and the axis ranges are fixed so the view doesn’t rescale as the path moves.

The view can be rotated (drag) and zoomed (scroll) while the data stream: the widget keeps the current view through each update, and holds updates while a 3D plot is being dragged or scrolled, applying them when you let go (an update during a drag would undo most of it).

library(shiny)
library(plotly.core)

window <- 5 # seconds shown
rate <- 10 # points per second
n <- window * rate # points kept on the path

# tan(s) jumps from +Inf to -Inf where s passes pi/2 + k * pi: k, the branch
branch <- function(s) floor(s / pi + 0.5)

# The path at times s, with a gap (NA) before each point on a new branch
path <- function(s) {
  copies <- 1 + c(FALSE, diff(branch(s)) != 0)
  t <- rep(s, copies)
  gap <- duplicated(rep(seq_along(s), copies), fromLast = TRUE)
  list(
    x = ifelse(gap, NA, sin(t)),
    y = ifelse(gap, NA, cos(t)),
    z = ifelse(gap, NA, tan(t))
  )
}

# a square plot (up to 700 px wide)
ui <- fluidPage(div(style = "max-width: 700px", plotlyOutput("path3d", height = "700px")))

server <- function(input, output, session) {
  last <- as.numeric(Sys.time()) # time of the newest point

  output$path3d <- renderPlotly({
    s <- last - seq(window, 0, length.out = n)
    p <- path(s)
    go_figure() |>
      add_scatter3d(x = p$x, y = p$y, z = p$z, mode = "lines", name = "path") |>
      add_scatter3d(x = I(sin(last)), y = I(cos(last)), z = I(tan(last)),
                    mode = "markers", marker = list(size = 6), name = "tip") |>
      update_layout(
        scene = list(
          xaxis = list(range = c(-1.1, 1.1)),
          yaxis = list(range = c(-1.1, 1.1)),
          zaxis = list(range = c(-10, 10)),
          aspectmode = "cube"
        ),
        legend = list(orientation = "h", y = 1, yanchor = "bottom"), # above the plot
        margin = list(l = 0, r = 0, t = 30, b = 0)
      )
  })

  proxy <- plotlyProxy("path3d", session)

  observe({
    invalidateLater(1000 / rate)
    s <- as.numeric(Sys.time())
    p <- lapply(path(c(last, s)), `[`, -1) # the new point, after a gap if any
    last <<- s
    plotlyProxyInvoke(
      proxy,
      "extendTraces",
      list(
        x = list(I(p$x), I(sin(s))),
        y = list(I(p$y), I(cos(s))),
        z = list(I(p$z), I(tan(s)))
      ),
      I(c(0L, 1L)),
      # per attribute, the points kept by each trace: n on the path, 1 tip
      list(x = c(n, 1L), y = c(n, 1L), z = c(n, 1L))
    )
  })
}

shinyApp(ui, server)

In the browser:

Show the code: the same update in JavaScript
path3d <- go_figure() |>
  add_scatter3d(x = numeric(), y = numeric(), z = numeric(), mode = "lines", name = "path") |>
  add_scatter3d(x = numeric(), y = numeric(), z = numeric(), mode = "markers",
                marker = list(size = 6), name = "tip") |>
  update_layout(
    height = 700,
    legend = list(orientation = "h", y = 1, yanchor = "bottom"),
    margin = list(l = 0, r = 0, t = 30, b = 0),
    scene = list(
      xaxis = list(range = c(-1.1, 1.1)),
      yaxis = list(range = c(-1.1, 1.1)),
      zaxis = list(range = c(-10, 10)),
      aspectmode = "cube"
    )
  )
htmlwidgets::onRender(as_widget(path3d), "
function(el) {
  var n = 50, step = 100;
  var branch = function(s) { return Math.floor(s / Math.PI + 0.5); };
  var last = Date.now() / 1000 - 5;
  // the new point at time s, after a gap (null) where tan(s) changes branch
  var points = function(s) {
    var p = {x: [], y: [], z: []};
    if (branch(s) !== branch(last)) { p.x.push(null); p.y.push(null); p.z.push(null); }
    p.x.push(Math.sin(s)); p.y.push(Math.cos(s)); p.z.push(Math.tan(s));
    last = s;
    return p;
  };
  // as the widget does for proxy calls: no updates while the view is being
  // rotated or zoomed, and the current view kept through each update
  var held = false, wheelUntil = 0;
  el.addEventListener('pointerdown', function() { held = true; }, true);
  window.addEventListener('pointerup', function() { held = false; });
  el.addEventListener('wheel', function() { wheelUntil = Date.now() + 400; }, true);
  var add = function(s) {
    var p = points(s);
    var scene = el._fullLayout && el._fullLayout.scene && el._fullLayout.scene._scene;
    if (scene) el.layout.scene.camera = scene.getCamera();
    Plotly.extendTraces(el,
      {x: [p.x, [Math.sin(s)]], y: [p.y, [Math.cos(s)]], z: [p.z, [Math.tan(s)]]},
      [0, 1], {x: [n, 1], y: [n, 1], z: [n, 1]});
  };
  for (var i = n - 1; i >= 0; i--) add(Date.now() / 1000 - i * step / 1000);
  setInterval(function() {
    if (held || Date.now() < wheelUntil) return;
    // catch up on the points held back, one every 100 ms
    var now = Date.now() / 1000;
    for (var t = Math.max(last + step / 1000, now - 5); t <= now; t += step / 1000) add(t);
  }, step);
}")

A heatmap

A heatmap can stream too. Here the x axis is time (the last 60 seconds), the y axis runs from 0 to 2π, and the colour is sin(y) · cos(t mod 2π), so each column is a sine wave scaled by where the time is in its 2π-second cycle. Ten times a second the app adds a column.

extendTraces appends to arrays, and a heatmap’s z is an array of rows. With transpose = TRUE each row of z is a column of the heatmap (one time), so a new time is one new row: z = list(list(column)) adds column to trace 0, and maxPoints keeps the last 600 times.

library(shiny)
library(plotly.core)

window <- 60 # seconds shown
rate <- 10 # columns per second
n <- window * rate # columns kept
y <- seq(0, 2 * pi, length.out = 61)

stamp <- function(t) format(t, "%Y-%m-%d %H:%M:%OS3")
# The column at time t: sin(y) * cos(t mod 2 pi)
column <- function(t) sin(y) * cos(as.numeric(t) %% (2 * pi))

ui <- fluidPage(plotlyOutput("heat"))

server <- function(input, output, session) {
  output$heat <- renderPlotly({
    times <- Sys.time() - seq(window, 0, length.out = n)
    go_figure() |>
      add_heatmap(
        x = stamp(times),
        y = y,
        z = t(vapply(times, column, numeric(length(y)))), # a row per time
        transpose = TRUE, # rows of z are columns of the heatmap
        zmin = -1,
        zmax = 1,
        colorscale = "RdBu"
      ) |>
      update_layout(yaxis_title = "y (radians)")
  })

  proxy <- plotlyProxy("heat", session)

  observe({
    invalidateLater(1000 / rate)
    t <- Sys.time()
    plotlyProxyInvoke(
      proxy,
      "extendTraces",
      list(x = list(I(stamp(t))), z = list(list(column(t)))),
      I(0L),
      n
    )
  })
}

shinyApp(ui, server)

zmin and zmax fix the colour scale, so colours don’t shift as the range of the data in the window changes.

In the browser:

Show the code: the same update in JavaScript
heat <- go_figure() |>
  add_heatmap(x = character(), y = seq(0, 2 * pi, length.out = 61), z = list(),
              transpose = TRUE, zmin = -1, zmax = 1, colorscale = "RdBu") |>
  update_layout(height = 400, yaxis_title = "y (radians)", xaxis_type = "date")
htmlwidgets::onRender(as_widget(heat), "
function(el) {
  var n = 600, step = 100, tau = 2 * Math.PI, y = [];
  for (var j = 0; j <= 60; j++) y.push(j / 60 * tau);
  var pad = function(v, w) { return String(v).padStart(w || 2, '0'); };
  var stamp = function(d) {
    return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' +
      pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' +
      pad(d.getMilliseconds(), 3);
  };
  // the column at time t (ms): sin(y) * cos(t mod 2 pi)
  var column = function(t) {
    var c = Math.cos(((t / 1000) % tau + tau) % tau);
    return y.map(function(v) { return Math.sin(v) * c; });
  };
  var now = Date.now(), x = [], z = [];
  for (var i = n - 1; i >= 0; i--) { var t = now - i * step; x.push(stamp(new Date(t))); z.push(column(t)); }
  Plotly.extendTraces(el, {x: [x], z: [z]}, [0], n);
  setInterval(function() {
    var t = Date.now();
    Plotly.extendTraces(el, {x: [[stamp(new Date(t))]], z: [[column(t)]]}, [0], n);
  }, step);
}")

Notes

  • One plot per session. renderPlotly() and the observer run for each browser session, so every viewer gets their own stream; they stop when the session ends.
  • A window by points, not time. maxPoints keeps the last 600 points, which is 60 seconds only while updates arrive every 100 ms. A busy server sends them less often, so the window covers a little more time. To show exactly the last 60 seconds, also set the axis range on each update with plotlyProxyInvoke(proxy, "relayout", list(xaxis.range = stamp(c(t - window, t)))) (at the cost of a second redraw), or drop points by time on your side.
  • Batching. Each plotlyProxyInvoke() is a message to the browser and a redraw. For faster data, collect points and send several at once (e.g. list(x = list(x_new, x_new), y = list(y1_new, y2_new)) every 250 ms): the plot looks the same, with less overhead.
  • Times. Strings like "2026-11-17 12:00:00.100" are read by plotly.js as dates in the browser’s time zone; format them in the time zone you want shown. Numbers (e.g. seconds) work too, on a numeric axis.
  • Large windows. extendTraces redraws the whole trace. With tens of thousands of points per trace, use add_scattergl(), which draws with WebGL.
  • The first render. plotlyProxy() sends its calls after Shiny’s next flush (deferUntilFlush = TRUE), so updates made while the plot is first drawn aren’t lost.