Charts that mirror a notebook.
In my NPTEL notebooks I draw interactive figures with plotly.graph_objects: a figure, a few traces, an update_layout call. The same library runs in the browser, and the same dictionaries describe the same figure. On this page we draw the spanning-fraction curve from the percolation lesson, let a slider change the board size, and read cluster labels off a heatmap by pointing at it.
Series overview · Previous: A board that redraws · Next: A cluster in three dimensions
What we are going to build
For each occupation probability \(p\) we generate forty random boards and count how many have a cluster reaching from the top row to the bottom row. The curve steepens as the board grows, which is the finite-size picture of a percolation threshold. Hover over a point to read its value; drag a box to zoom; double-click to reset.
Release the slider to recompute. Each point averages forty boards.
From the notebook to the page
Plotly's Python package builds a JSON description of the figure and hands it to the JavaScript library, which does the drawing. Writing the JavaScript directly skips the middle step. The names are the same; only the syntax around them changes.
| In the notebook | In the page |
|---|---|
import plotly.graph_objects as go | <script src="https://cdn.plot.ly/plotly-3.1.0.min.js">, or load it on demand as below |
go.Scatter(x=x, y=y, mode='lines+markers', name='4 neighbors') | {type: 'scatter', x, y, mode: 'lines+markers', name: '4 neighbors'} |
go.Heatmap(z=labels, hovertemplate=...) | {type: 'heatmap', z: labels, hovertemplate: ...} |
fig = go.Figure(data=[...]) | the array of trace objects |
fig.update_layout(xaxis_title='p', ...) | one layout object: {xaxis: {title: {text: 'p'}}, ...} |
fig.show() | Plotly.newPlot(element, data, layout, config) |
| re-running the cell | Plotly.react(element, data, layout, config) |
go.Frame and fig.frames | Plotly.animate(element, frames, options) |
ipywidgets.interact(f, size=(16, 64)) | a range input whose listener calls Plotly.react |
Underscored Python keywords such as xaxis_title are shorthand for nested dictionaries. In JavaScript we write the nesting out: xaxis: {title: {text: 'p'}}. Everything else carries over unchanged, including color names, dash styles and hover templates.
Step 1: Load the library only when needed
The full Plotly bundle is about four and a half megabytes. That is acceptable for a notebook on a laptop and painful on a phone, so we add the script tag only when a chart is about to appear, and remember the promise so that a page with several charts loads the library once.
Loading the code…
Step 2: Compute the data separately
The sweep is plain JavaScript and knows nothing about charts. It is the same loop we would write in the notebook: for twenty-one values of \(p\) from 0.1 to 0.9, the fraction of boards with a spanning cluster. Keeping the calculation apart from the drawing means it can be tested in Node, without a browser, and reused by a different chart.
Loading the code…
Step 3: Traces are plain objects
Compare this with the Python: go.Scatter(x=four.x, y=four.y, mode='lines+markers', name='4 neighbors', line=dict(color='#32658f')). The JavaScript object has the same keys. The one addition is type: 'scatter', which in Python is implied by the class name.
Loading the code…
Step 4: The layout
This is the update_layout call. Transparent backgrounds let the chart sit on the page in both light and dark themes, and the text color is read from the page at mount time rather than fixed in the file. The two dotted lines mark the thresholds from the literature, 0.593 for edge contacts and 0.407 for edge and corner contacts.
Loading the code…
Step 5: Redraw with Plotly.react
Plotly.newPlot is fig.show(). Plotly.react takes the same arguments but updates the existing chart in place, keeping the zoom where it can, which is what a slider needs. We listen for change rather than input because each sweep takes a fraction of a second on a 64 × 64 board, and recomputing on every pixel of slider travel would feel sticky.
Loading the code…
Step 6: A heatmap with hover readouts
Here is the reason to use Plotly at all: the hover readout. Point at any cell and read its cluster label. The hovertemplate string is identical to the one we would pass to go.Heatmap in Python. The reversed \(y\) axis and the scaleanchor keep the board square and in reading order, the way a NumPy array prints.
Loading the code…
Step 7: Mount when visible
An IntersectionObserver watches each chart container and mounts it when the container comes within 300 pixels of the viewport. A reader who never scrolls this far never downloads the library.
Loading the code…
When Plotly is worth it
Plotly earns its download when the reader needs to hover, zoom, pan or export, or when the figure is a standard chart with axes, legends and color bars that would be tedious to draw by hand. It is the wrong tool for schematic drawings, cartoon panels or boards with speech bubbles, which is why most figures on this site are hand-drawn SVG. For a page with one or two charts, the smaller plotly-basic bundle, about a megabyte, covers scatter, bar and pie traces; heatmaps and 3D traces need the full bundle.
What to try
- Change
boardsfrom 40 to 200 in the slider handler and watch the curve smooth out, and the recompute slow down. Lesson 5 moves this loop into a Web Worker. - Add
error_yto the traces. The standard error of a fraction \(f\) from \(n\) boards is \(\sqrt{f(1-f)/n}\). - Take one of the Plotly figures from an optimization notebook, call
fig.to_json()in Python, and pass the resulting data and layout straight toPlotly.newPlot. Nothing needs translating by hand.
Series overview · Previous: A board that redraws · Next: A cluster in three dimensions
Plotly.js is released under the MIT license by Plotly, Inc. and loaded from cdn.plot.ly when a chart scrolls into view.