Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 31 ยท Plotly

Plotly.js in the Browser

Use Plotly.js directly in the browser: load it from a CDN, call newPlot, update with react and extendTraces, handle click, hover and relayout events.

Every Plotly chart you make in Python, R or Julia is drawn by one JavaScript library: plotly.js. Python's fig.show() writes a JSON description of the figure and hands it to plotly.js running in a browser. If you write a website, a dashboard front end or a notebook widget, you can skip Python completely and call plotly.js yourself, using the same data and layout objects you met in Plotly Figures: Data, Layout and Traces.

This lesson shows the plain JavaScript workflow: load the library, draw with Plotly.newPlot, update when the data changes, and react to what the user does. That last part is the main reason to use JavaScript directly: a click on a point can open a detail panel, and a zoom can trigger a new data request.

plotly.js is a large library that is not loaded on this site, so the code that calls Plotly is read-only here. The runnable examples are stand-ins: a small event emitter and a tiny update engine written in plain JavaScript that behave like the real thing in the ways that matter (events with a payload, nested update paths, a rolling buffer). They show the mechanism, not Plotly's real rendering.

Loading Plotly.js

You have three common options. The simplest is a script tag from a CDN. Pin an exact version so a new release can never change your page without you noticing (the number below is a placeholder; use the current release from the Plotly download page):

HTML
<script src="https://cdn.plot.ly/plotly-3.x.y.min.js" charset="utf-8"></script>

The script creates a global called Plotly. With a bundler you install a package and import it instead:

Terminal
npm install plotly.js-dist-min
JavaScript
import Plotly from "plotly.js-dist-min";

Why bundle size matters

The full plotly.js bundle is large: several megabytes before compression, because it contains every chart type, including 3D, maps and statistical traces. That is fine for an internal tool or a data-heavy page, and it is a real cost on a blog post that needs one bar chart. Plotly publishes partial bundles that contain only some trace types, for example plotly.js-basic-dist-min (bar, scatter and pie), plotly.js-cartesian-dist-min (most 2D charts) and others. Check the size reduction in your own build before and after switching, and keep in mind that modern browsers no longer share cached CDN files between sites, so a big script is downloaded once per site. If your page only needs a handful of simple charts, an alternative such as a smaller SVG library may be the better choice; see Choosing the Right Chart for the design side of that decision.

Drawing with Plotly.newPlot

Plotly.newPlot(target, data, layout, config) draws a chart into a <div>. The first argument is the element or its id. data is an array of traces, layout describes everything outside the traces, and config controls the interface (toolbar, responsiveness).

HTML
<div id="sales" style="height: 360px"></div>
<script>
  const data = [
    {
      type: "bar",
      x: ["Jan", "Feb", "Mar", "Apr"],
      y: [120, 150, 90, 180],
      name: "Revenue",
    },
  ];
  const layout = {
    title: { text: "Revenue by month" },
    yaxis: { title: { text: "USD (thousands)" } },
    margin: { t: 50 },
  };
  const config = { responsive: true, displaylogo: false };

  Plotly.newPlot("sales", data, layout, config);
</script>

Two settings are worth remembering. responsive: true makes the chart resize with its container, which you want almost always. And the <div> must have a height (here set in the style), because plotly.js does not invent one for a div with no content.

The rule of thumb that makes plotly.js easy: the chart is a function of two plain objects. You can log them, save them as JSON, send them over the network or write tests against them. There is no hidden state except what the user did in the browser (zoom, selection).

Updating a chart

When the data changes you do not call newPlot again. Plotly gives you several update functions, from broad to narrow:

Function What it does
Plotly.react(target, data, layout, config) Re-render from new full objects; Plotly works out what changed.
Plotly.restyle(target, update, traceIndices) Change trace attributes, such as { "marker.color": "tomato" }.
Plotly.relayout(target, update) Change layout attributes, such as { "xaxis.range": [0, 10] }.
Plotly.extendTraces(target, update, traceIndices, maxPoints) Append points to traces; maxPoints keeps a rolling window.
Plotly.purge(target) Remove the chart and free its resources.

Plotly.react is the best fit for code that already keeps the whole state in a variable, as React, Vue or a hand-written render function does: you rebuild data and layout and call react, and Plotly compares them with the previous ones and redraws only the difference. To stop it from resetting the user's zoom on every update, set layout.uirevision to a constant value; as long as the value stays the same, user interactions such as zoom and legend toggles are kept.

JavaScript
const state = { values: [3, 5, 4] };

function render() {
  Plotly.react(
    "chart",
    [{ type: "scatter", mode: "lines+markers", y: state.values }],
    { uirevision: "keep-zoom", title: { text: "Live values" } }
  );
}

setInterval(() => {
  state.values.push(Math.round(Math.random() * 10));
  render();
}, 1000);

For a stream that adds a point at a time, extendTraces is cheaper because it does not touch the existing points:

JavaScript
Plotly.extendTraces("chart", { y: [[nextValue]] }, [0], 100);

The update argument has one array per trace (here one trace, so [[nextValue]]), and the last argument keeps only the newest 100 points.

The next example is a stand-in for the update functions. It implements nested paths such as "xaxis.range[0]" in a few lines, which is the idea behind relayout and restyle, and a rolling window like the maxPoints argument.

JS Nested update paths and a rolling window (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can see that a dotted path reaches into nested objects and creates missing levels. That is why updates like { "xaxis.range": [0, 5] } are short, and why a typo in a path creates a new, ignored attribute in a naive implementation. (Real Plotly validates paths and warns about unknown attributes in its development tooling.)

Events: click, hover and relayout

The graph div is also an event source. You attach handlers with .on(eventName, handler) after the chart is drawn. Plotly sends a payload that describes what happened:

JavaScript
const chart = document.getElementById("sales");

chart.on("plotly_click", (event) => {
  const point = event.points[0];
  console.log(point.x, point.y, point.curveNumber, point.pointNumber);
});

chart.on("plotly_hover", (event) => {
  showTooltip(event.points[0]);
});

chart.on("plotly_relayout", (changes) => {
  if ("xaxis.range[0]" in changes) {
    loadDataBetween(changes["xaxis.range[0]"], changes["xaxis.range[1]"]);
  }
});

The most useful events are:

  • plotly_click, plotly_hover and plotly_unhover: event.points lists the touched points with x, y, curveNumber (which trace) and pointNumber (which row of the trace).
  • plotly_selected: after a box or lasso selection; event.points is the selected set.
  • plotly_relayout: after zoom, pan or an explicit relayout; the payload holds the changed layout paths, like xaxis.range[0].
  • plotly_restyle: after a trace attribute changed, for example a legend click that hides a trace.

A handler on plotly_relayout is how you build a "load more detail when zoomed in" feature. Be careful not to call relayout from inside the same handler without a guard, or you create an infinite loop.

sequenceDiagram
    participant U as User
    participant P as Plotly graph div
    participant H as Your handler
    U->>P: click a point
    P->>H: plotly_click with event.points
    H->>P: Plotly.restyle (highlight the point)
    P-->>U: redrawn chart

A click goes into Plotly, comes out as an event, and your handler can change the chart again.

The second example is a stand-in for event delivery. It builds a tiny graph with on and emit, finds the nearest point to a click, and delivers a payload in the same shape as plotly_click.

JS Event emitter with click and relayout payloads (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the handler never touches pixels. It receives the data coordinates and the trace and row indexes, which is what you need to look up the full record in your own data.

Python and JavaScript together

If you build figures in Python, you can still use the JavaScript side. fig.to_json() gives the figure as a JSON string and fig.write_html("page.html") writes a standalone page. A web app can send the figure JSON from the server and pass its data and layout fields straight to Plotly.newPlot or Plotly.react. The Python library plotly.io also has to_html for embedding a chart as an HTML fragment. These export options are covered in Exporting, Embedding and Sharing Charts.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call draws a new chart into a div with the id 'sales'?

    Plotly.newPlot takes the target, the array of traces and the layout object. purge removes a chart and on is an event method of the graph div.
  2. 2. How do you keep the user's zoom when you call Plotly.react again with new data?

    Plotly keeps user interactions as long as uirevision stays the same between updates. Changing the value tells Plotly to reset them.
  3. 3. What does the maxPoints argument of Plotly.extendTraces do?

    After appending the new values, Plotly trims each trace to the last maxPoints points. This is how streaming charts avoid growing forever.
  4. 4. A handler for plotly_relayout receives { 'xaxis.range[0]': 2, 'xaxis.range[1]': 4 }. What happened?

    The payload lists the layout paths that changed. Both range ends changed, which is what happens when the user zooms or pans the x axis.
  5. 5. Why might you use a partial bundle such as plotly.js-basic-dist-min?

    Partial bundles contain only some trace types, so the download is smaller. The trade-off is that traces outside the bundle will not draw.

Summary

  • plotly.js draws every Plotly chart; you can call it directly with plain data, layout and config objects.
  • Load it from a CDN with a pinned version or install plotly.js-dist-min; the full bundle is several megabytes, and partial bundles are smaller.
  • Plotly.newPlot draws once; react, restyle, relayout and extendTraces update; purge cleans up.
  • Dotted paths like "xaxis.range[0]" address nested attributes; uirevision preserves user zoom across updates.
  • Handlers attached with .on("plotly_click" | "plotly_hover" | "plotly_selected" | "plotly_relayout", fn) receive points or changed layout paths.
  • The Plotly calls in this lesson are read-only here; the runnable examples are plain-JavaScript stand-ins.

Next: Dashboards with Dash and Callbacks, where Python handles these events for you.