D3.js is a JavaScript library, so Python's job is to prepare the data and hand it over as JSON. For a file you can share, insert df.to_json(orient="records") into an HTML template that loads D3. For a chart in Jupyter that talks back to Python, wrap the D3 code in an anywidget class. This post uses D3 7.9 and anywidget 0.11.
Quick Example
This writes stations.html, a bar chart of bike trips with a hover effect. Open the file in a browser.
from pathlib import Path
import pandas as pd
df = pd.DataFrame({
"station": ["Central", "Harbor", "Library", "Stadium", "Museum", "Market"],
"trips": [1840, 1315, 980, 760, 610, 1120],
}).sort_values("trips", ascending=False)
template = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>
<style>
#stations { max-width: 640px; font: 13px sans-serif; }
#stations rect { fill: #0b7285; }
#stations rect:hover { fill: #f08c00; }
</style>
</head>
<body>
<div id="stations"></div>
<script>
const data = __DATA__;
const width = 640, height = data.length * 40 + 20, left = 80;
const x = d3.scaleLinear([0, d3.max(data, d => d.trips)], [left, width - 60]);
const y = d3.scaleBand(data.map(d => d.station), [10, height - 10]).padding(0.2);
const svg = d3.select("#stations").append("svg")
.attr("viewBox", [0, 0, width, height]);
svg.selectAll("rect").data(data).join("rect")
.attr("x", left)
.attr("y", d => y(d.station))
.attr("height", y.bandwidth())
.attr("width", 0)
.transition().duration(800)
.attr("width", d => x(d.trips) - left);
svg.selectAll(".value").data(data).join("text")
.attr("class", "value")
.attr("x", d => x(d.trips) + 6)
.attr("y", d => y(d.station) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.text(d => d3.format(",")(d.trips));
svg.append("g")
.attr("transform", `translate(${left},0)`)
.call(d3.axisLeft(y).tickSize(0))
.call(g => g.select(".domain").remove())
.attr("font-size", 13);
</script>
</body>
</html>
"""
data_json = df.to_json(orient="records").replace("</", "<\\/")
html = template.replace("__DATA__", data_json)
Path("stations.html").write_text(html, encoding="utf-8")
Central has the most trips, 1,840, about three times Museum's 610.
How the Data Gets From pandas to D3
df.to_json(orient="records") produces a list of objects such as {"station":"Central","trips":1840}, the shape D3 examples expect. Three details save debugging time:
- Don't use an f-string for the template. JavaScript and CSS are full of braces. Replace a placeholder such as
__DATA__instead. - Escape
</. A text value containing</script>would otherwise end the script block early..replace("</", "<\\/")keeps the JSON the same. - Convert dates yourself. Use
date_format="iso", then parse the strings in JavaScript withnew Date(d.date).
A Beeswarm Plot With D3's Force Simulation
D3 earns its extra code for layouts that Python libraries don't give you directly. This beeswarm uses d3.forceSimulation() to place 220 sample 10 km race times without overlap.
import numpy as np
rng = np.random.default_rng(19)
groups = {"Under 30": (49, 7), "30 to 49": (53, 8), "50 and over": (61, 9)}
times = pd.DataFrame(
[(group, round(float(t), 1))
for (group, (mean, sd)), n in zip(groups.items(), [70, 90, 60])
for t in rng.normal(mean, sd, n)],
columns=["group", "minutes"],
)
swarm_template = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/d3.min.js"></script>
<style> #swarm { max-width: 640px; font: 13px sans-serif; } </style>
</head>
<body>
<div id="swarm"></div>
<script>
const data = __DATA__;
const width = 640, height = 390, radius = 4;
const groups = [...new Set(data.map(d => d.group))];
const x = d3.scaleLinear(d3.extent(data, d => d.minutes), [110, width - 20]).nice();
const y = d3.scaleBand(groups, [10, height - 40]);
const color = d3.scaleOrdinal(groups, ["#1971c2", "#7048e8", "#c2255c"]);
// Pull each dot toward its time and its group's row, and keep dots apart.
d3.forceSimulation(data)
.force("x", d3.forceX(d => x(d.minutes)).strength(1))
.force("y", d3.forceY(d => y(d.group) + y.bandwidth() / 2))
.force("collide", d3.forceCollide(radius + 0.6))
.stop()
.tick(200);
const svg = d3.select("#swarm").append("svg").attr("viewBox", [0, 0, width, height]);
svg.append("g").attr("transform", `translate(0,${height - 40})`)
.call(d3.axisBottom(x));
svg.append("text").attr("x", width / 2).attr("y", height - 6)
.attr("text-anchor", "middle").text("10 km time (minutes)");
svg.selectAll(".group").data(groups).join("text")
.attr("class", "group").attr("x", 10)
.attr("y", d => y(d) + y.bandwidth() / 2).attr("dy", "0.35em").text(d => d);
svg.selectAll("circle").data(data).join("circle")
.attr("cx", d => d.x).attr("cy", d => d.y).attr("r", radius)
.attr("fill", d => color(d.group))
.append("title").text(d => `${d.group}: ${d.minutes} min`);
</script>
</body>
</html>
"""
swarm_html = swarm_template.replace("__DATA__", times.to_json(orient="records"))
Path("race-times.html").write_text(swarm_html, encoding="utf-8")
Older groups are shifted toward slower times. Hover over a dot to see its time.
How Do I Show D3 in a Jupyter Notebook?
For a one-way chart, put the HTML in an iframe. Scripts inside plain HTML() output don't run reliably in notebooks, and the iframe also keeps your CSS from leaking into the page.
from html import escape
from IPython.display import HTML
HTML(f'<iframe srcdoc="{escape(html)}" width="680" height="300" '
'style="border:0"></iframe>')
Build a Two-Way D3 Widget With anywidget
anywidget turns a JavaScript module into a Jupyter widget. Traits marked sync=True are shared: Python changes redraw the chart, and model.set() followed by model.save_changes() sends values back.
import anywidget
import ipywidgets as widgets
import traitlets
class BarChart(anywidget.AnyWidget):
_esm = """
import * as d3 from "https://cdn.jsdelivr.net/npm/[email protected]/+esm";
function render({ model, el }) {
const width = 600, row = 34, left = 90;
const svg = d3.select(el).append("svg").attr("width", width)
.attr("fill", "currentColor").attr("font-size", 13);
function draw() {
const data = model.get("data");
const x = d3.scaleLinear([0, d3.max(data, d => d.trips)], [left, width - 60]);
svg.attr("height", data.length * row);
const bars = svg.selectAll("g").data(data, d => d.station).join(enter => {
const g = enter.append("g").style("cursor", "pointer");
g.append("rect").attr("x", left).attr("height", row - 7);
g.append("text").attr("class", "name").attr("x", left - 8)
.attr("y", 18).attr("text-anchor", "end");
g.append("text").attr("class", "value").attr("y", 18);
return g;
});
bars.attr("transform", (d, i) => `translate(0,${i * row})`)
.on("click", (event, d) => {
model.set("selected", d.station);
model.save_changes();
});
bars.select("rect")
.attr("fill", d => d.station === model.get("selected") ? "#e8590c" : "#0b7285")
.attr("width", d => x(d.trips) - left);
bars.select(".name").text(d => d.station);
bars.select(".value").attr("x", d => x(d.trips) + 6)
.text(d => d3.format(",")(d.trips));
}
model.on("change:data", draw);
model.on("change:selected", draw);
draw();
}
export default { render };
"""
data = traitlets.List().tag(sync=True)
selected = traitlets.Unicode("").tag(sync=True)
chart = BarChart(data=df.to_dict(orient="records"))
message = widgets.Label("Click a bar")
def show_selection(change):
trips = df.set_index("station").loc[change["new"], "trips"]
message.value = f"Python received: {change['new']} ({trips:,} trips)"
chart.observe(show_selection, names="selected")
widgets.VBox([chart, message])
Clicking the Library bar sends its name to Python, which updates the label underneath:

Assigning new data from Python, such as chart.data = new_df.to_dict(orient="records"), redraws the bars. Assign a new list; changing the existing one in place doesn't trigger an update.
For longer widgets, move the JavaScript into its own file and set _esm = pathlib.Path("bar_chart.js"). With the environment variable ANYWIDGET_HMR=1, saving the file reloads the widget without restarting the kernel.
Which Approach Should I Use?
| Goal | Approach |
|---|---|
| Send someone an interactive file, or put a chart on a website | HTML template with JSON data |
| Look at a chart in a notebook | The same HTML in an iframe |
| Use clicks or selections in Python, or update a chart live | anywidget |
| Draw a standard chart type | Plotly, Bokeh or Altair, with no JavaScript to write |
Use D3 when you need a design those libraries can't produce. You write the scales, axes and events yourself.

