Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 44 ยท Real-world Charts and Integration

Reusable Charts and Responsive Design

Package D3 code as a reusable chart function with getters and setters, make SVG charts responsive with viewBox and ResizeObserver, and handle margins and updates.

The charts in tutorials are written as one long script. In a real site you need the same chart on ten pages, with different data, different sizes and updates when data changes. D3 has a long tradition of solving this with a small pattern called a reusable chart. Combined with a responsive SVG, it lets you write a chart once and drop it anywhere.

The reusable chart pattern

A chart is a function that returns a function. The outer function holds configuration in a closure and exposes getters and setters; the inner function draws into a selection:

JavaScript
function barChart() {
  let width = 480, height = 280;
  let margin = { top: 10, right: 10, bottom: 30, left: 40 };
  let x = d => d.label, y = d => d.value;
  let color = "#4263eb";

  function chart(selection) {
    selection.each(function (data) {
      // draw using width, height, x, y, color ...
    });
  }

  chart.width  = function (v) { return arguments.length ? (width = v, chart) : width; };
  chart.height = function (v) { return arguments.length ? (height = v, chart) : height; };
  chart.x      = function (v) { return arguments.length ? (x = v, chart) : x; };
  chart.y      = function (v) { return arguments.length ? (y = v, chart) : y; };
  chart.color  = function (v) { return arguments.length ? (color = v, chart) : color; };
  return chart;
}

Each setter returns chart so calls chain, and with no argument it returns the current value. That is exactly how all D3 APIs behave (scale.domain(), axis.ticks()), so your charts feel familiar. You use it like this:

JavaScript
const chart = barChart().width(600).color("tomato");
d3.select("#a").datum(dataA).call(chart);
d3.select("#b").datum(dataB).call(chart);

selection.call(chart) passes the selection to the function. datum() stores the data on the container, and selection.each lets the chart read it per container, so one chart instance can draw into several containers.

A modern alternative is a plain function with an options object, or an ES class with a update(data) method. They are equally valid; the closure style is common in the D3 ecosystem, and the options-object style is easier to type in TypeScript:

JavaScript
function barChart(container, { data, width = 480, height = 280, color = "#4263eb" }) { /* ... */ return { update(newData) {} }; }

Draw once, update many times

A good reusable chart separates setup (create the SVG, groups and axes one time) from update (bind data and set attributes). The update step uses selection.join() with a key function, so you get correct enter, update and exit behaviour for free, and can add a transition for smooth changes.

A reusable bar chart with update()

Press the buttons repeatedly: the second call does not create a second SVG, because every container is created with selectAll(...).data([null]).join(...), a handy idiom for "make exactly one of these if missing". Bars slide, grow and shrink between data sets.

Making an SVG responsive

Hard-coded width="480" breaks on a phone. SVG has a built-in scaling system, the viewBox:

JavaScript
svg.attr("viewBox", [0, 0, width, height])   // the internal coordinate system
   .style("width", "100%")
   .style("height", "auto");                  // keep the aspect ratio

Everything inside is drawn as if the SVG were width x height, then scaled to the available size. Fonts scale too, so labels get small on narrow screens. For charts with lots of text, a second approach is better: measure the container and re-render with the real width.

JavaScript
const ro = new ResizeObserver(entries => {
  const { width } = entries[0].contentRect;
  chart.width(width).height(Math.max(220, width * 0.5));
  host.datum(data).call(chart);
});
ro.observe(host.node());

ResizeObserver fires when the element changes size (not only the window), so it also works in split panes and dashboards. Debounce expensive redraws, and disconnect the observer (ro.disconnect()) when the chart is removed.

Technique Pros Cons
viewBox scaling trivial, no JS text scales with the chart
Re-render on resize crisp text, can change layout (fewer ticks on mobile) more code
CSS container queries on the wrapper adjust sizes of HTML parts does not change SVG coordinates

On small screens consider changing the design, not only the scale: fewer ticks (axis.ticks(width / 80)), shorter labels, rotated or hidden tick text, a legend below the chart instead of beside it.

The margin convention

Keep one margin object and compute inner sizes (innerWidth = width - m.left - m.right). Draw axes in groups translated by the margins; scale ranges use the inner box. Mixing absolute numbers all over the code is the main source of bugs when you later change the size.

flowchart TD
  A["chart() closure: config"] --> B["call(selection): setup once"]
  B --> C["update: scales from data + size"]
  C --> D["join + transition"]
  E["ResizeObserver or new data"] --> C

Setup once, update whenever data or size changes.

Common mistakes

  • Appending a new svg on every update. Use the data([null]).join(...) idiom or check empty().
  • Using arrow functions for chart setters that rely on arguments; arrow functions have no own arguments. Use function, as the TryIt above does.
  • Reading window.innerWidth instead of the container size.
  • Not cleaning up observers and event listeners when a chart is destroyed, which leaks memory in long-lived apps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a setter such as chart.width(v) usually return when called with an argument?

    Returning the chart enables chaining; called with no argument it acts as a getter.
  2. 2. What is the effect of svg.attr('viewBox', [0, 0, 480, 260]) together with width 100%?

    viewBox defines the internal coordinates; the browser scales them to the element's rendered size.
  3. 3. Why is ResizeObserver better than window resize events for charts?

    A container can change size without the window changing (sidebars, panes, tabs).
  4. 4. What does selectAll('svg').data([null]).join('svg') ensure?

    A one-element data array gives a one-element join, an idiom for 'create if missing'.

Summary

  • Write charts as closures with chainable getters and setters, or as functions taking an options object.
  • Separate one-time setup from an update() that joins data with a key and transitions.
  • Use viewBox for simple scaling or ResizeObserver plus re-render for crisp, adaptive charts.
  • Keep a margin object and compute inner sizes once.

Next: Loading and Cleaning Data