Introduction to responsiveness


To build a graph, you need to know the width and height of the SVG area.

However, we often don't know the exact dimensions we need for our visualizations; we just want them to fit their container.

This module explains how to make a chart responsive. It provides the code for a hook that detects changes in a div's dimensions and explains how to inject its returned values into a visualization component.

Free
4 minutes read

What is responsiveness?

Responsiveness refers to the ability of a data visualization (such as charts, graphs, or dashboards) to adapt and display correctly across different devices and screen sizes.

This ensures that users have an optimal viewing experience whether they are accessing the visualizations on a desktop, tablet, or mobile device

This density chart is responsive! Resize your window to see how the graph fits its container.

Responsiveness is a key aspect of web development. This module specifically focuses on making charts responsive. It won't cover general topics like CSS, Flexbox, Grid, or other concepts related to overall website responsiveness.

Design Considerations

A graph can appear visually appealing when its width exceeds its height, but it may lose its effectiveness if shrunk too much. In some cases, using a completely different chart type on smaller screens, removing a chart, or flipping it may be necessary.

This course offers technical guidelines on making graphs responsive. It focuses on the "how" rather than the "what," providing you with the tools to achieve your desired outcomes.

😢 Unresponsive chart

When building a chart with JavaScript, knowing its dimensions — width and height — is essential. These dimensions are needed to compute scales, draw axes, and determine where to place shapes.

Consequently, a visualization component always expects width and heightproperties.

Consider a simple density plot, for example. The code looks like this:

import * as d3 from "d3";

type DensityProps = {
  width: number; // 🙁 not responsive!
  height: number; // 🙁 not responsive!
  data: number[];
};

export const DensityPlot = ({ width, height, data }: DensityProps) => {

  // read the data, make scales, compute svg elements using the dimensions

  return (
    <div>
      <svg width={width} height={height}> // pass the dimensions to the svg area
        // render the shape
      </svg>
    </div>
  );
};

Let's Code

Let's assume we have a div that is responsive and takes the full width of an app.

How can we draw a chart inside this div that also takes up the entire space and remains responsive?

Let's find out! 🙇