liveBook · Manning

D3.range()

As explained in D3.js in Action, Third Edition

d3.range() is a D3-array function that generates an arithmetic sequence of numeric values.

d3.range() generates an arithmetic sequence of numbers. In a responsive Van Gogh visualization, range(1881, 1891) creates the ten years used for small multiples; the ending value is excluded. section 14.4.1

The resulting array also drives layout calculations: its length determines the number of grid rows after the number of columns changes with screen width. section 14.4.1

Generate visualization years

import { range } from "d3-array"; const years = range(1881, 1891); // [1881, 1882, ..., 1890] section 14.4.1

Listing 14.3 Dynamically updating the height (Grid.svelte)
<script>
  import { range } from "d3-array";

  ...

  const years = range(1881, 1891);                    #1
  let numColumns;                                      #2
  $: switch (true) {                                  
    case windowWidth > 900:                          
      numColumns = 3;                                 
      break;                                          
    case windowWidth <= 900 && windowWidth > 600:     
      numColumns = 2;                                
      break;                                          
    default:                                          
      numColumns = 1;                                
  }                                                   
  $: numRows = Math.ceil(years.length / numColumns);   #3
  $: smWidth = svgWidth / numColumns;                  #4
  $: smHeight = smWidth + 40;                       
  $: svgHeight = numRows * smHeight;                  #5
</script>

<svelte:window bind:innerWidth={windowWidth} />

{#if svgWidth && svgHeight}                            #6
     <svg width={svgWidth} height={svgHeight} />      
{/if}                                                 

<style>
  svg {
    border: 1px solid magenta;
  }
</style>

See the complete responsive-grid implementation, including range-generated years, column-dependent row counts, and reactive SVG height. section 14.4.1

How D3.js in Action, Third Edition covers it

How deep it goes
Defines a numeric sequence and applies its length to row calculations, without detailing the function’s implementation.
Examples
Uses range(1881, 1891) to generate ten years for a Van Gogh small-multiple grid.
What it assumes
Assumes basic JavaScript arrays and imports while demonstrating the function through a responsive visualization.
What you can do after
Build a numeric array that can supply visualization items and support responsive layout calculations.
How it connects
Connects numeric sequences with D3-array, responsive SVG, Svelte reactivity, and small multiples.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.