# How to Make D3.js Charts From Python

> Use D3.js with Python: pass pandas data to a D3 chart as JSON in a standalone HTML file, show it in Jupyter, or build a two-way D3 widget with anywidget.

Source: https://www.pythoncharts.com/python/d3-from-python/ | Published: 2026-11-27 | Author: Alex Scott | Category: Python | Tags: d3, javascript, anywidget, jupyter, interactive charts

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](https://anywidget.dev/) 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.

```python
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">
<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>
</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")
```

<style>
  #stations { max-width: 640px; font: 13px sans-serif; }
  #stations rect { fill: #0b7285; }
  #stations rect:hover { fill: #f08c00; }
</style>
<div id="stations"></div>
![D3 horizontal bar chart of bike trips: Central 1,840, Harbor 1,315, Market 1,120, Library 980, Stadium 760, Museum 610](https://www.pythoncharts.com/python/d3-from-python/images/d3-bar-chart.png)

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 with `new 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.

```python
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">
<style> #swarm { max-width: 640px; font: 13px sans-serif; } </style>
</head>
<body>
<div id="swarm"></div>
</body>
</html>
"""

swarm_html = swarm_template.replace("__DATA__", times.to_json(orient="records"))
Path("race-times.html").write_text(swarm_html, encoding="utf-8")
```

<style> #swarm { max-width: 640px; font: 13px sans-serif; } </style>
<div id="swarm"></div>
![D3 beeswarm plot of 10 km race times for three age groups, with the oldest group shifted toward slower times](https://www.pythoncharts.com/python/d3-from-python/images/d3-beeswarm.png)

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.

```python
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.

```python
import anywidget
import ipywidgets as widgets
import traitlets

class BarChart(anywidget.AnyWidget):
    _esm = """
    import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7.9.0/+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:

![D3 bar chart widget in a Jupyter notebook with the Library bar highlighted in orange and a line below reading Python received: Library (980 trips)](https://www.pythoncharts.com/python/d3-from-python/images/d3-anywidget.png)

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](https://www.pythoncharts.com/plotly/plotly-tutorial/), [Bokeh](https://www.pythoncharts.com/bokeh/bokeh-tutorial/) or [Altair](https://www.pythoncharts.com/altair/intro-to-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.

## Similar Topics

- [Embedding Interactive Charts in a Website](https://www.pythoncharts.com/python/embed-interactive-charts-website/)
- [Interactive Matplotlib Plots in Jupyter](https://www.pythoncharts.com/matplotlib/matplotlib-interactive-jupyter/)
- [Network Graphs in Python](https://www.pythoncharts.com/python/network-graph-python/)
