D3 Layouts & Scrollytelling

COP 4283 syllabus

Lecture 24 · November 19, 2026

Force layouts & network graphs

Lab ZIP

01Force simulation

JavaScript
async function build() {
  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1000 - margin.left - margin.right,
      height = 650 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  let nodes = [{}, {}, {}, {}, {}]

  // Create a force simulation for the nodes with a 'tick' event listener. 
  // The 'tick' function is called on every tick of the simulation, allowing us to update the nodes' positions.
  const simulation = d3.forceSimulation(nodes)
      .on('tick', ticked);

  simulation
      .force('center', d3.forceCenter(width / 2, height / 2)) // Positions the nodes around the center of the SVG container.
      .force('charge', d3.forceManyBody().strength(-100)) // Negative strength repels the nodes.
  // .force("charge", d3.forceManyBody()
  //     .strength(-10) // Sets the repulsion strength to -10.
  //     .distanceMax(50) // Specifies the maximum distance over which the repelling force is applied.
  // );

  function ticked() {

      svg.selectAll('circle')
          .data(nodes)
          .join('circle')
          .attr('r', 10)
          
          .attr('cx', d => d.x)
          .attr('cy', d => d.y)
          .style('fill', '#fdc8aa');
  }
}

build();
Result
Loading…
Data & source

Lecture 24, slides 4–8

Based on the supplied student-lab tutorial. Local data and libraries; responsive SVG preview.

02Collision detection

JavaScript
async function build() {
  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1000 - margin.left - margin.right,
      height = 650 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  //forceCollide
  const numNodes = 100
  let nodes = d3.range(numNodes).map(function (d) {
      return { radius: Math.random() * 25 }
  })

  let simulation = d3.forceSimulation(nodes)
      .force('charge', d3.forceManyBody().strength(5)) // need a positive value
      .force('center', d3.forceCenter(width / 2, height / 2))
      .force('collision', d3.forceCollide().radius(d => d.radius + 1))
      .on('tick', ticked)

  function ticked() {
      svg .selectAll('circle')
          .data(nodes)
          .join('circle')
          .style('fill', '#fdc8aa')
          .style('stroke', '#bd3246')
          .attr('r', d => d.radius)
          .attr('cx', d => d.x)
          .attr('cy', d => d.y);
  }
}

build();
Result
Loading…
Data & source

Lecture 24, slides 9–10

Based on the supplied student-lab tutorial. Local data and libraries; responsive SVG preview.

03Force X and Y

JavaScript
async function build() {
  // This tutorial is based on https://www.d3indepth.com/force-layout/

  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1000 - margin.left - margin.right,
      height = 650 - margin.top - margin.bottom;

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  const numNodes = 100

  const nodes = d3.range(numNodes).map(function (d) {
      return { radius: Math.random() * 25, category: Math.floor(Math.random() * 3) }
  })

  const xCenter = [width * 0.2, width * 0.5, width * 0.8];

  let simulation = d3.forceSimulation(nodes)
      .force('charge', d3.forceManyBody().strength(5))
      .force('center', d3.forceCenter(width / 2, height / 2))
      .force('collision', d3.forceCollide().radius(d => d.radius))
      .force('x', d3.forceX().x(function (d) {
          return xCenter[d.category];
      }))
      .force('y', d3.forceY(height / 2).strength(0.1))
      .on('tick', ticked)

  const colorArray = ['#d9f9f4', '#9cd9de', '#86c1d4']

  function ticked() {
      svg.selectAll('circle')
          .data(nodes)
          .join('circle')
          .style('fill', d => colorArray[d.category])
          .style('stroke', '#a6b1e1')
          .attr('r', d => d.radius)
          .attr('cx', d => d.x)
          .attr('cy', d => d.y);
  }
}

build();
Result
Loading…
Data & source

Lecture 24, slides 11–13

Based on the supplied student-lab tutorial. Local data and libraries; responsive SVG preview.

04Income beeswarm solution

JavaScript
async function build() {
  // Load and process data
  await d3.csv("datasets/normal_family_income_data.csv", d => ({
      Family_Income: +d.Family_Income
  })).then(data => {

      initializeChart(data);
  });

  // Initialize the chart with the processed data
  function initializeChart(data) {
      const svgWidth = 1280, svgHeight = 800;
      const margin = { top: 50, right: 150, bottom: 150, left: 40 };
      const width = svgWidth - margin.left - margin.right;
      const height = svgHeight - margin.top - margin.bottom;

      const svg = d3.select(".chart-container").append("svg")
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .append("g")
          .attr("transform", `translate(${margin.left},${margin.top})`);

      // X scale
      const x = d3.scaleLinear()
          .domain([0, d3.max(data, d => d.Family_Income)])
          .range([0, width]);

      // Add X axis on top
      svg.append("g")
          .attr('class', 'axis')
          .attr("transform", `translate(0,${height / 2 - 10})`)
          .call(d3.axisTop(x))
          .selectAll('text')
          .style('font-size', 20);

      svg.append("text")
          .attr("fill", "#fff")
          .attr("x", width + 130)
          .attr("y", height / 2 - 10)
          .style("text-anchor", "end")
          .text("Family Income")
          .style("font-size", 18);

      drawHistogram(svg, data, x, height);
      drawStripPlot(svg, data, x, height);
  }

  // Draw strip plot
  function drawStripPlot(svg, data, xScale, chartHeight) {

      // Define the force simulation
      const simulation = d3.forceSimulation(data)
          .force("x", d3.forceX(d => xScale(d.Family_Income)).strength(1))
          .force("y", d3.forceY(chartHeight * 0.8).strength(0.1))
          .force("collide", d3.forceCollide(6))
          .on("tick", () => {
              svg.selectAll("circle")
                  .data(data)
                  .join("circle")
                  .attr("r", 5)
                  .attr("cx", d => d.x)
                  .attr("cy", d => d.y)
                  .style("fill", "#FF655A")
                  .style("opacity", 0.9);
          });
  }

  // Draw histogram
  function drawHistogram(svg, data, xScale, chartHeight) {
      const histogram = d3.histogram()
          .value(d => d.Family_Income)
          .domain(xScale.domain())
          .thresholds(xScale.ticks(40));

      const bins = histogram(data);
      const yHist = d3.scaleLinear()
          .range([chartHeight / 2, 0])
          .domain([0, d3.max(bins, d => d.length)]);

      const bar = svg.selectAll(".bar")
          .data(bins)
          .enter().append("g")
          .attr("class", "bar")
          .attr("transform", d => `translate(${xScale(d.x0)},${yHist(d.length + 10)})`);

      bar.append("rect")
          .attr("x", 1)
          .attr("width", d => xScale(d.x1) - xScale(d.x0) - 1)
          .attr("height", d => chartHeight / 2 - yHist(d.length))
          .style("fill", "#00B0F0")
  }
}

build();
Result
Loading…
Data & source

Lecture 24, slides 14

Completed from the supplied instructor solution. Local data and libraries; responsive SVG preview.

06Network labels

JavaScript
async function build() {
  const margin = { top: 30, right: 30, bottom: 70, left: 60 },
      width = 1000 - margin.left - margin.right,
      height = 600 - margin.top - margin.bottom;

  const data = {
      "nodes": [
          { "id": "A", "group": 1 },
          { "id": "B", "group": 2 },
          { "id": "C", "group": 2 },
          { "id": "D", "group": 3 },
          { "id": "E", "group": 3 },
          { "id": "F", "group": 3 }
      ],
      "links": [
          { "source": "A", "target": "B", "value": 2 },
          { "source": "A", "target": "C", "value": 1 },
          { "source": "B", "target": "D", "value": 3 },
          { "source": "C", "target": "E", "value": 2 },
          { "source": "C", "target": "F", "value": 1 },
          { "source": "D", "target": "E", "value": 1 },
          { "source": "E", "target": "F", "value": 2 }
      ]
  }

  // append the svg object to the body of the page
  const svg = d3.select("#main")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)

  // set up the simulation
  const simulation = d3.forceSimulation(data.nodes)
      .force("link", d3.forceLink(data.links).id(d => d.id))
      .force("charge", d3.forceManyBody().strength(-100))
      .force("center", d3.forceCenter(width/2, height/2));

  // create the links
  const links = svg
      .selectAll("line")
      .data(data.links)
      .join("line")
      .style("stroke-width", d => d.value)
      .style('stroke', '#D3D3D3');

  // create the nodes
  // const nodes = svg
  //     .selectAll("circle")
  //     .data(data.nodes)
  //     .join("circle")
  //     .attr("r", 10)
  //     .style("fill", d => d3.schemeCategory10[d.group]);

  /* ------------------------- adding label for nodes ------------------------- */
  const nodeGroups = svg.selectAll(".nodeGroup")
      .data(data.nodes)
      .join("g")
      .attr('class', 'nodeGroup')

  nodeGroups.append('circle')
      .attr("r", 10)
      .style("fill", d => d3.schemeObservable10[d.group])

  nodeGroups.append('text')
      .text(d => d.id)
      .attr('dy', 5)
      .style('text-anchor', 'middle')
      .style('fill', 'white')

  // update the positions of the nodes and links on each tick of the simulation
  simulation.on("tick", function () {
      links
          .attr("x1", d => d.source.x)
          .attr("y1", d => d.source.y)
          .attr("x2", d => d.target.x)
          .attr("y2", d => d.target.y);

      nodeGroups
          .attr('transform', d => 'translate(' + d.x + ',' + d.y + ')')
  });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 30–32

Based on the supplied student-lab tutorial. Local data and libraries; responsive SVG preview.

07Les Misérables network solution

JavaScript
async function build() {
  // Select SVG and extract dimensions directly
  const svg = d3.select('svg'),
      width = +svg.attr('width'),
      height = +svg.attr('height');

  // Define scales
  const colorScale = d3.scaleOrdinal(d3.schemeObservable10),
      linkScale = d3.scaleSqrt().range([1, 5]);

  // Load and process data
  await d3.json('datasets/les_miserables.json').then((network) => {

      // Define force simulation
      const simulation = d3.forceSimulation(network.nodes)
          .force("link", d3.forceLink(network.links).id(d => d.id))
          .force('charge', d3.forceManyBody())
          .force('center', d3.forceCenter(width / 2, height / 2))
          .on('tick', tickSimulation);

      // You can also setup simulation with nodes and links separately 
      // simulation.nodes(network.nodes).on('tick', tickSimulation);
      // simulation.force('link').links(network.links);

      // Update link scale domain
      linkScale.domain(d3.extent(network.links, d => d.value));

      // Append groups for links and nodes
      const linkG = svg.append('g').attr('class', 'links-group'),
          nodeG = svg.append('g').attr('class', 'nodes-group');

      // Append links
      linkG.selectAll('.link')
          .data(network.links)
          .join('line')
          .attr('class', 'link')
          .style('stroke-width', d => linkScale(d.value))
          .style('stroke', '#D3D3D3')
          .style('stroke-opacity', 0.5);

      // Append nodes
      nodeG.selectAll('.node')
          .data(network.nodes)
          .join('circle')
          .attr('class', 'node')
          .attr('r', 6)
          .style('fill', d => colorScale(d.group));

      // Tick simulation to update positions
      function tickSimulation() {
          linkG.selectAll('.link')
              .attr('x1', d => d.source.x)
              .attr('y1', d => d.source.y)
              .attr('x2', d => d.target.x)
              .attr('y2', d => d.target.y);

          nodeG.selectAll('.node')
              .attr('cx', d => d.x)
              .attr('cy', d => d.y);
      }
  });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 33

Completed from the supplied instructor solution. Local data and libraries; responsive SVG preview.

08Drag nodes

JavaScript
async function build() {
  const svg = d3.select('svg');
  const width = +svg.attr('width');
  const height = +svg.attr('height');

  const colorScale = d3.scaleOrdinal(d3.schemeObservable10);
  const linkScale = d3.scaleSqrt().range([1, 5]);

  let toolTip = d3.tip()
      .attr("class", "d3-tip")
      .offset([-3, 0])
      .html(function (event, d) {
          return "<h5>" + d['id'] + "</h5>";
      });

  // Call tooltip to initialize it to document and svg
  svg.call(toolTip);

  await d3.json('datasets/les_miserables.json').then((dataset) => {

      const simulation = d3.forceSimulation()
          .force('link', d3.forceLink().id(d => d.id))
          .force('charge', d3.forceManyBody())
          .force('center', d3.forceCenter(width / 2, height / 2));

      const drag = d3.drag()
          .on('start', dragstarted)
          .on('drag', dragged)
          .on('end', dragended);

      linkScale.domain(d3.extent(dataset.links, d => d.value));

      const linkG = svg.append('g').attr('class', 'links-group');
      const nodeG = svg.append('g').attr('class', 'nodes-group');

      const linkEnter = linkG.selectAll('.link')
          .data(dataset.links)
          .join('line')
          .attr('class', 'link')
          .style('stroke-width', d => linkScale(d.value))
          .style('stroke', '#D3D3D3')
          .style('stroke-opacity', 0.5);

      const nodeEnter = nodeG.selectAll('.node')
          .data(dataset.nodes)
          .join('circle')
          .attr('class', 'node')
          .attr('r', 6)
          .style('fill', d => colorScale(d.group))
          .on('mouseover', toolTip.show)
          .on('mouseout', toolTip.hide)
          .call(drag)

      simulation.nodes(dataset.nodes).on('tick', () => {
          linkEnter
              .attr('x1', d => d.source.x)
              .attr('y1', d => d.source.y)
              .attr('x2', d => d.target.x)
              .attr('y2', d => d.target.y);

          nodeEnter
              .attr('cx', d => d.x)
              .attr('cy', d => d.y);
      });

      simulation.force('link').links(dataset.links);

      function dragstarted(event, d) {
          // If the simulation is cooling down, reheat it
          if (!event.active) simulation.alphaTarget(0.3).restart();
          // Fix the position of the node (fx, fy are fixed x and y positions)
          d.fx = event.x;
          d.fy = event.y;
      }

      // Called when dragging: updates the fixed position of the dragged node
      function dragged(event, d) {
          // Update the fixed positions to the current event position
          d.fx = event.x;
          d.fy = event.y;
      }

      // Called when drag ends: allows the node to move freely again
      function dragended(event, d) {
          // If the simulation is active, cool it down
          if (!event.active) simulation.alphaTarget(0);
          // Release the fixed positions so the node can move freely again
          d.fx = null;
          d.fy = null;
      }

  });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 34–35

Based on the supplied student-lab tutorial. Local data and libraries; responsive SVG preview.

09Pin and release nodes

JavaScript
async function build() {
  const svg = d3.select('svg');
  const width = +svg.attr('width');
  const height = +svg.attr('height');

  const colorScale = d3.scaleOrdinal(d3.schemeObservable10);
  const linkScale = d3.scaleSqrt().range([1, 5]);

  let toolTip = d3.tip()
      .attr("class", "d3-tip")
      .offset([-12, 0])
      .html(function (event, d) {
          return "<h5>" + d['id'] + "</h5>";
      });

  // Call tooltip to initialize it to document and svg
  svg.call(toolTip);

  await d3.json('datasets/les_miserables.json').then((dataset) => {

      const simulation = d3.forceSimulation()
          .force('link', d3.forceLink().id(d => d.id))
          .force('charge', d3.forceManyBody())
          .force('center', d3.forceCenter(width / 2, height / 2));

      const drag = d3.drag()
          .on('start', dragstarted)
          .on('drag', dragged)
          .on('end', dragended);

      linkScale.domain(d3.extent(dataset.links, d => d.value));

      const linkG = svg.append('g').attr('class', 'links-group');
      const nodeG = svg.append('g').attr('class', 'nodes-group');

      const linkEnter = linkG.selectAll('.link')
          .data(dataset.links)
          .join('line')
          .attr('class', 'link')
          .style('stroke-width', d => linkScale(d.value))
          .style('stroke', '#D3D3D3')
          .style('stroke-opacity', 0.5);

      const nodeEnter = nodeG.selectAll('.node')
          .data(dataset.nodes)
          .join('circle')
          .attr('class', 'node')
          .attr('r', 6)
          .style('fill', d => colorScale(d.group))
          .on('mouseover', toolTip.show)
          .on('mouseout', toolTip.hide)
          .call(drag)
          .on('click', click)

      simulation.nodes(dataset.nodes).on('tick', () => {
          linkEnter
              .attr('x1', d => d.source.x)
              .attr('y1', d => d.source.y)
              .attr('x2', d => d.target.x)
              .attr('y2', d => d.target.y);

          nodeEnter
              .attr('cx', d => d.x)
              .attr('cy', d => d.y);
      });

      simulation.force('link').links(dataset.links);

      // Handlers for drag events on nodes
      // Drag events adjust the [fx,fy] of the nodes to override the simulation
      function dragstarted(event, d) {
          d3.select(this).classed("fixed", true);
          if (!event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
      }
      function dragged(event, d) {
          d.fx = event.x;
          d.fy = event.y;
      }

      function dragended(event, d) {
          if (!event.active) simulation.alphaTarget(0);
      }

      function click(event, d) {
          // Remove the fixed x (fx) and fixed y (fy) positions of the node
          // This allows the node to move freely again in the simulation
          delete d.fx;
          delete d.fy;

          // Remove the "fixed" class from the node, potentially changing its style
          // to indicate it is no longer fixed in place
          d3.select(this).classed("fixed", false);

          // Restart the simulation with full alpha (energy),
          // causing the layout to adjust immediately
          simulation.alpha(1).restart();
      }
  });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 36–37

Based on the supplied student-lab tutorial. Local data and libraries; responsive SVG preview.

10Connected nodes solution

JavaScript
async function build() {
  let svg = d3.select('svg');
  let width = +svg.attr('width');
  let height = +svg.attr('height');

  let colorScale = d3.scaleOrdinal(d3.schemeObservable10)
  let linkScale = d3.scaleSqrt().range([1, 5]);

  let toolTip = d3.tip()
      .attr("class", "d3-tip")
      .offset([-12, 0])
      .html(function (event, d) {
          return "<h5>" + d['id'] + "</h5>";
      });

  // Call tooltip to initialize it to document and svg
  svg.call(toolTip);

  await d3.json('datasets/les_miserables.json').then(function (dataset) {

      const network = dataset;

      let simulation = d3.forceSimulation()
          .force('link', d3.forceLink().id(function (d) { return d.id; }))
          .force('charge', d3.forceManyBody())
          .force('center', d3.forceCenter(width / 2, height / 2));

      let drag = d3.drag()
          .on('start', dragstarted)
          .on('drag', dragged)
          .on('end', dragended);

      // Update link scale based on the extent of the link values
      linkScale.domain(d3.extent(network.links, function (d) { return d.value; }));

      // Create separate link & node group elements
      // Ensures that links show below nodes
      let linkG = svg.append('g')
          .attr('class', 'links-group');
      let nodeG = svg.append('g')
          .attr('class', 'nodes-group');

      const linkEnter = linkG.selectAll('.link')
          .data(dataset.links)
          .join('line')
          .attr('class', 'link')
          .style('stroke-width', d => linkScale(d.value))
          .style('stroke', '#D3D3D3')
          .style('stroke-opacity', 0.5);

      const nodeEnter = nodeG.selectAll('.node')
          .data(dataset.nodes)
          .join('circle')
          .attr('class', 'node')
          .attr('r', 6)
          .style('fill', d => colorScale(d.group))
          .call(drag)
          .on('click', click)
          .on('mouseover', (event, d) => mouseover(event, d))
          .on('mouseout', mouseout)
          .call(drag) // Call drag object to setup all drag listeners for nodes
          .on("click", click)

      // Set up the nodes for the simulation
      // Note this has to be done before we set up the links in the next block
      simulation
          .nodes(dataset.nodes)
          .on('tick', tickSimulation);

      // Set up the links and what type of force will be used for the simulation
      // Again note that this has to be done in a separate block from above
      simulation
          .force('link')
          .links(dataset.links);

      // Tick simulation callback called on every iteration of the simulation
      // Think of ticks like frames of a video file
      function tickSimulation() {
          linkEnter
              .attr('x1', function (d) { return d.source.x; })
              .attr('y1', function (d) { return d.source.y; })
              .attr('x2', function (d) { return d.target.x; })
              .attr('y2', function (d) { return d.target.y; });

          nodeEnter
              .attr('cx', function (d) { return d.x; })
              .attr('cy', function (d) { return d.y; });
      }

      /* ------------------------ highlight connected nodes ----------------------- */
      function mouseover(event, d) {
          toolTip.show(event, d)
          
          let connectedLinks = network.links.filter(l => l.source.id === d.id || l.target.id === d.id)

          let connectedNodes = [d.id, ...connectedLinks.map(l => l.source.id), ...connectedLinks.map(l => l.target.id)]

          d3.selectAll('.node')
              .style('opacity', dNode => connectedNodes.includes(dNode.id) ? 1 : 0.2)
          d3.selectAll('.link')
              .style('stroke', linkD => connectedLinks.map(l => l.index).includes(linkD.index) ? 'red' : '#D3D3D3')
      }
      function mouseout(event, d) {
          toolTip.hide()
          d3.selectAll('.node')
              .style('opacity', 1)
          d3.selectAll('.link')
              .style('stroke', '#D3D3D3')
      }

      function dragstarted(event, d) {
          d3.select(this).classed("fixed", true);
          if (!event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
      }

      function dragged(event, d) {
          d.fx = event.x;
          d.fy = event.y;
      }

      function dragended(event, d) {
          if (!event.active) simulation.alphaTarget(0);
      }

      function click(event, d) {
          delete d.fx;
          delete d.fy;
          d3.select(this).classed("fixed", false);
          simulation.alpha(1).restart();
      }
  });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 38–39

Completed from the supplied instructor solution. Local data and libraries; responsive SVG preview.

Scrollytelling & animation

11Side-by-side story

JavaScript
async function build() {
  // Based on https://pudding.cool/process/introducing-scrollama/
  // Using d3 for convenience

  // Select DOM elements
  const main = d3.select("main");
  const scrolly = main.select("#scrolly");
  const svg = scrolly.select("svg");
  const article = scrolly.select("article");
  const step = article.selectAll(".step");

  // Initialize the scrollama instance
  const scroller = scrollama();

  // Initialize the scrollytelling setup
  function init() {
      // Force a resize on load to ensure proper dimensions
      handleResize();

      // Set up scrollama with options and bind event handlers
      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.5,
              progress: true,
              debug: false
          })
          .onStepEnter(function (response) {

              // Highlight the current step
              step.classed("is-active", (d, i) => i === response.index);

              // Update the step-specific text in the SVG
              d3.select('#step-text')
                  .text(`Step ${response.index + 1}`);
          })
          .onStepProgress(function (response) {

              // Update the progress-specific text in the SVG
              d3.select('#progress-text')
                  .text(`Progress ${(response.progress * 100).toFixed(0)}%`);
          });

      // Add text elements for step and progress if they don't already exist

      svg.append('text')
          .attr('id', 'step-text')
          .text('Step 1')
          .attr('transform', 'translate(40, 150)')
          .attr('fill', 'white')
          .style('font-size', '30px');

      svg.append('text')
          .attr('id', 'progress-text')
          .text('Progress 0%')
          .attr('transform', 'translate(40, 250)')
          .attr('fill', 'white')
          .style('font-size', '30px');

      // Add a resize event listener
      window.addEventListener('resize', handleResize);
  }

  // Generic window resize listener
  function handleResize() {
      // Update the height of step elements
      const stepHeight = Math.floor(window.innerHeight * 0.5);
      step.style("height", `${stepHeight}px`);

      // Set up SVG dimensions and positioning
      const svgHeight = window.innerHeight * 0.75;
      const svgMarginTop = (window.innerHeight - svgHeight) / 2;

      svg.attr("viewBox", "0 0 500 400");
      svg
          .style("height", `${svgHeight}px`)
          .style("top", `${svgMarginTop}px`);

      // Notify scrollama to update element dimensions
      scroller.resize();
  }

  // Kick things off
  init();
}

build();
Result
Loading…
Data & source

Lecture 24, slides 44–59

Based on the supplied student-lab tutorial. Scroll inside the result, or expand it; the story works in both directions.

12Overlay story

JavaScript
async function build() {
  // Based on https://pudding.cool/process/introducing-scrollama/
  // Using d3 for convenience

  // Select DOM elements
  const main = d3.select("main");
  const scrolly = main.select("#scrolly");
  const svg = scrolly.select("svg");
  const article = scrolly.select("article");
  const step = article.selectAll(".step");

  // Initialize the scrollama instance
  const scroller = scrollama();

  // Initialize the scrollytelling setup
  function init() {
      // Force a resize on load to ensure proper dimensions
      handleResize();

      // Set up scrollama with options and bind event handlers
      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.5,
              // debug: false,
          })
          .onStepEnter(function (response) {

              // Highlight the current step
              step.classed("is-active", (d, i) => i === response.index);

              // Update the title text in the SVG
              d3.select('#title-index')
                  .text(`Visualization ${response.index + 1}`);
          })

      // Add a title text element if it doesn't already exist
      svg.append('text')
          .attr('id', 'title-index')
          .attr('transform', 'translate(40, 200)')
          .style('font-size', '36px')
          .attr('fill', 'white')
          .text('Visualization 1');

      // Add a resize event listener
      window.addEventListener('resize', handleResize);
  }

  function handleResize() {
      const stepHeight = Math.floor(window.innerHeight * 0.5);
      step.style("height", `${stepHeight}px`);

      const svgHeight = window.innerHeight * 0.75;
      const svgMarginTop = (window.innerHeight - svgHeight) / 2;

      svg.attr("viewBox", "0 0 500 400");
      svg
          .style("height", `${svgHeight}px`)
          .style("top", `${svgMarginTop}px`);

      // Notify scrollama to update element dimensions
      scroller.resize();
  }

  // Kick things off
  init();
}

build();
Result
Loading…
Data & source

Lecture 24, slides 60

Based on the supplied student-lab tutorial. Scroll inside the result, or expand it; the story works in both directions.

13Chart switching solution

JavaScript
async function build() {
  let activeStep = 0;
  let storyReady = false;

  let main = d3.select("main");
  let scrolly = main.select("#scrolly");
  let svg = scrolly.select("svg");
  let article = scrolly.select("article");
  let step = article.selectAll(".step");

  let barData, scatterPlotData;

  const margin = { top: 40, right: 150, bottom: 60, left: 100 };
  let svgWidth = 1000;
  let width = svgWidth - margin.left - margin.right;
  let height = 500;

  let scroller = scrollama();

  await Promise.all([
      d3.csv("datasets/country-values.csv"),
      d3.csv("datasets/housing.csv")
  ]).then(([bar, scatter]) => {
      barData = bar;
      scatterPlotData = scatter;
      init();
  });

  function init() {
      handleResize();
      renderBarChart();
      renderScatterPlot();

      d3.select('.barGroup').style('display', 'none');
      d3.select('.scatterGroup').style('display', 'none');

      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.33,
          })
          .onStepEnter(handleStepEnter);

      window.addEventListener('resize', handleResize);
  }

  function handleResize() {
      let stepH = Math.floor(window.innerHeight * 0.75);
      step.style("height", stepH + "px");

      svgWidth = 1000;
      width = svgWidth - margin.left - margin.right;
      let svgHeight = height + margin.top + margin.bottom;

      svg
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .attr("viewBox", "0 0 " + svgWidth + " " + svgHeight);

      svg.selectAll("*").remove();

      svg.append('g')
          .attr('class', 'barGroup')
          .attr('transform', `translate(${margin.left},${margin.top})`);

      svg.append('g')
          .attr('class', 'scatterGroup')
          .attr('transform', `translate(${margin.left},${margin.top})`);

      renderBarChart();
      renderScatterPlot();

      scroller.resize();
      if (storyReady) handleStepEnter({ index: activeStep, direction: "down" });
  }

  function handleStepEnter(response) {
      activeStep = response.index;
      step.classed("is-active", (d, i) => i === response.index);
      const action = stepActions[response.index];
      if (action) action();
  }

  const stepActions = {
      0: () => showOnly('.barGroup'),
      1: () => showOnly('.barGroup'),
      2: () => showOnly('.scatterGroup'),
      3: () => showOnly('.barGroup'),
      4: () => showOnly('.scatterGroup'),
  };

  function hideAll() {
      d3.select('.barGroup').style('display', 'none');
      d3.select('.scatterGroup').style('display', 'none');
  }

  function showOnly(selector) {
      hideAll();
      d3.select(selector).style('display', 'block');
  }

  function renderBarChart() {
      let group = d3.select('.barGroup');
      group.selectAll("*").remove();

      let x = d3.scaleBand()
          .domain(barData.map(d => d.Country))
          .range([0, width])
          .padding(0.1);

      let y = d3.scaleLinear()
          .domain([0, d3.max(barData, d => +d.Value)])
          .nice()
          .range([height, 0]);

      group.append("g")
          .selectAll(".bar")
          .data(barData)
          .join("rect")
          .attr("class", "bar")
          .attr("x", d => x(d.Country))
          .attr("y", d => y(+d.Value))
          .attr("width", x.bandwidth())
          .attr("height", d => height - y(+d.Value))
          .attr("fill", "#69b3a2");

      const xAxis = group.append("g")
          .attr("transform", `translate(0,${height})`)
          .call(d3.axisBottom(x));

      if (barData.length > 6) {
          xAxis.selectAll("text")
              .attr("transform", "rotate(-45)")
              .style("text-anchor", "end");
      }

      group.append("g")
          .call(d3.axisLeft(y));
  }

  function renderScatterPlot() {
      let group = d3.select('.scatterGroup');
      group.selectAll("*").remove();

      let x = d3.scaleLinear()
          .domain([0, d3.max(scatterPlotData, d => +d.GrLivArea)])
          .nice()
          .range([0, width]);

      let y = d3.scaleLinear()
          .domain([0, d3.max(scatterPlotData, d => +d.SalePrice)])
          .nice()
          .range([height, 0]);

      group.append("g")
          .selectAll(".dot")
          .data(scatterPlotData)
          .join("circle")
          .attr("class", "dot")
          .attr("cx", d => x(+d.GrLivArea))
          .attr("cy", d => y(+d.SalePrice))
          .attr("r", 3)
          .attr("fill", "#69b3a2");

      group.append("g")
          .attr("transform", `translate(0,${height})`)
          .call(d3.axisBottom(x));

      group.append("g")
          .call(d3.axisLeft(y));
  }

  storyReady = true;
  handleStepEnter({ index: 0, direction: "down" });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 61–63

Completed from the supplied instructor solution. Scroll inside the result, or expand it; the story works in both directions.

14Scroll transitions

JavaScript
async function build() {
  let activeStep = 0;
  let storyReady = false;

  let main = d3.select("main");
  let scrolly = main.select("#scrolly");
  let svg = scrolly.select("svg");
  let article = scrolly.select("article");
  let step = article.selectAll(".step");

  let barData, scatterPlotData;

  const margin = { top: 40, right: 150, bottom: 60, left: 100 };
  let svgWidth = 1000;
  let width = svgWidth - margin.left - margin.right;
  let height = 500;

  let scroller = scrollama();

  await Promise.all([
      d3.csv("datasets/country-values.csv"),
      d3.csv("datasets/housing.csv")
  ]).then(([bar, scatter]) => {
      barData = bar;
      scatterPlotData = scatter;
      init();
  });

  function init() {
      handleResize();
      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.33,
          })
          .onStepEnter(handleStepEnter)
          .onStepExit(handleStepExit);

      window.addEventListener('resize', handleResize);
  }

  function handleResize() {
      let stepH = Math.floor(window.innerHeight * 0.75);
      step.style("height", stepH + "px");

      svgWidth = 1000;
      width = svgWidth - margin.left - margin.right;
      let svgHeight = height + margin.top + margin.bottom;

      svg
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .attr("viewBox", "0 0 " + svgWidth + " " + svgHeight);

      svg.selectAll("*").remove();

      svg.append('g')
          .attr('class', 'barGroup')
          .attr('transform', `translate(${margin.left},${margin.top})`);

      svg.append('g')
          .attr('class', 'scatterGroup')
          .attr('transform', `translate(${margin.left},${margin.top})`);

      scroller.resize();
      if (storyReady) handleStepEnter({ index: activeStep, direction: "down" });
  }

  function handleStepEnter(response) {
      activeStep = response.index;
      step.classed("is-active", (d, i) => i === response.index);

      switch (response.index) {
          case 0:
              createBarChart();
              break;
          case 1:
              createBarChart();
              break;
          case 2:
              createBarChart();
              updateBar();
              break;
          case 3:
              createScatterplot();
              break;
          case 4:
              createScatterplot();
              updateScatterplot();
              break;
      }
  }

  function handleStepExit(response) {
      step.classed("is-active", (d, i) => i === response.index);

      switch (response.index) {
          case 2:
              shrinkBarChart();
              break;
      }
  }

  function createBarChart() {
      d3.select('.scatterGroup').style('display', 'none');

      let group = d3.select('.barGroup').style('display', 'block');

      group
          .transition()
          .duration(1000)
          .attr('transform', `translate(${margin.left},${margin.top})`);

      group.selectAll("*").remove();

      let x = d3.scaleBand()
          .domain(barData.map(d => d.Country))
          .range([0, width])
          .padding(0.1);

      let y = d3.scaleLinear()
          .domain([0, d3.max(barData, d => +d.Value)])
          .nice()
          .range([height, 0]);

      group.append("g")
          .selectAll(".bar")
          .data(barData)
          .join("rect")
          .attr("class", "bar")
          .attr("x", d => x(d.Country))
          .attr("y", d => y(+d.Value))
          .attr("width", x.bandwidth())
          .attr("height", d => height - y(+d.Value))
          .attr("fill", "#69b3a2");

      const xAxis = group.append("g")
          .attr("transform", `translate(0,${height})`)
          .call(d3.axisBottom(x));

      if (barData.length > 6) {
          xAxis.selectAll("text")
              .attr("transform", "rotate(-45)")
              .style("text-anchor", "end");
      }

      group.append("g")
          .call(d3.axisLeft(y));
  }

  function updateBar() {
      d3.select('.scatterGroup').style('display', 'none');

      let group = d3.select('.barGroup')
          .style('display', 'block')
          .transition()
          .duration(1000)
          .attr('transform', `translate(${margin.left},${margin.top + 100})`);

      // Rescale
      let x = d3.scaleBand()
          .domain(barData.map(d => d.Country))
          .range([0, width])
          .padding(0.1);

      let y = d3.scaleLinear()
          .domain([0, d3.max(barData, d => +d.Value)])
          .nice()
          .range([height, 0]);

      // Grow bars back
      d3.select('.barGroup').selectAll('rect')
          .transition()
          .duration(1000)
          .attr("y", d => y(+d.Value))
          .attr("height", d => height - y(+d.Value));
  }

  function shrinkBarChart() {
      d3.select('.barGroup').selectAll('rect')
          .transition()
          .duration(1000)
          .attr('y', height)
          .attr('height', 0);
  }

  function createScatterplot() {
      d3.select('.barGroup').style('display', 'none');
      let group = d3.select('.scatterGroup').style('display', 'block');
      group.selectAll("*").remove();

      let x = d3.scaleLinear()
          .domain([0, d3.max(scatterPlotData, d => +d.GrLivArea)])
          .nice()
          .range([0, width]);

      let y = d3.scaleLinear()
          .domain([0, d3.max(scatterPlotData, d => +d.SalePrice)])
          .nice()
          .range([height, 0]);

      group.append("g")
          .selectAll(".dot")
          .data(scatterPlotData)
          .join("circle")
          .attr("class", "dot")
          .attr("cx", d => x(+d.GrLivArea))
          .attr("cy", d => y(+d.SalePrice))
          .attr("r", 3)
          .attr("fill", "#69b3a2");

      group.append("g")
          .attr("transform", `translate(0,${height})`)
          .call(d3.axisBottom(x));

      group.append("g")
          .call(d3.axisLeft(y));
  }
  function updateScatterplot() {
      d3.select('.barGroup').style('display', 'none');

      let group = d3.select('.scatterGroup').style('display', 'block');

      group.selectAll(".dot")
          .transition()
          .duration(1000)
          .attr("r", 6)
          .attr("fill", "#ff7f0e");
  }

  storyReady = true;
  handleStepEnter({ index: 0, direction: "down" });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 64–65

Based on the supplied student-lab tutorial. Scroll inside the result, or expand it; the story works in both directions.

15Continent highlighting solution

JavaScript
async function build() {
  let activeStep = 0;
  let storyReady = false;

  let main = d3.select("main");
  let scrolly = main.select("#scrolly");
  let svg = scrolly.select("svg");
  let article = scrolly.select("article");
  let step = article.selectAll(".step");

  const margin = { top: 40, right: 150, bottom: 60, left: 100 };
  let svgWidth = 1000;
  let width = svgWidth - margin.left - margin.right;
  let height = 500;

  // initialize scrollama
  let scroller = scrollama();

  let data;

  const continentColor = d3.scaleOrdinal()
      .domain(["Asia", "Africa", "Europe", "Americas", "Oceania"])
      .range(["#f94144", "#f3722c", "#f9c74f", "#43aa8b", "#577590"]);

  // Load data and initialize
  await d3.csv("datasets/countries.csv").then(function (d) {
      data = d;
      init();
  });

  function init() {
      handleResize();

      // ✅ Only create the group once
      svg.selectAll('.scatterGroup').remove(); // Clean up if needed
      svg.append('g')
          .attr('class', 'scatterGroup');

      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.33,
          })
          .onStepEnter(handleStepEnter);

      window.addEventListener('resize', handleResize);
  }

  function handleResize() {
      let stepH = Math.floor(window.innerHeight * 0.75);
      step.style("height", stepH + "px");

      svgWidth = 1000;
      width = svgWidth - margin.left - margin.right;
      let svgHeight = height + margin.top + margin.bottom;

      svg
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .attr("viewBox", "0 0 " + svgWidth + " " + svgHeight);

      // svg.selectAll("*").remove();

      // svg.append('g')
      // .attr('class', 'scatterGroup')
      // .attr('transform', `translate(${margin.left},${margin.top})`);

      scroller.resize();
      if (storyReady) handleStepEnter({ index: activeStep, direction: "down" });
  }

  function handleStepEnter(response) {
      activeStep = response.index;

      step.classed("is-active", (d, i) => i === response.index);

      // ✅ Hide all chart elements before rendering or updating
      d3.selectAll(".myCircles").style("opacity", 0.1); // Optional: fade all first

      switch (response.index) {
          case 0:
              createCircles();
              d3.selectAll(".myCircles").style("opacity", 1);
              break;
          case 1:
              step2Highlight();
              break;
          case 2:
              step3Highlight();
              break;
          case 3:
              step4Highlight();
              break;
          default:
              break;
      }
  }

  function createCircles() {
      const maxHeight = 400, maxWidth = 600, originalCircleSize = 3;
      let xMax = d3.max(data.map(d => +d.lifeExp));
      let yMax = d3.max(data.map(d => +d.gdpPercap));

      const x = d3.scaleLinear()
          .domain([0, xMax]).nice()
          .range([0, maxWidth]);

      const y = d3.scaleLinear()
          .domain([0, yMax]).nice()
          .range([maxHeight, 0]);

      let scatterPlotGroup = d3.select('.scatterGroup')
          .attr('transform', 'translate(50,50)');

      scatterPlotGroup.selectAll('*').remove();
      let myCircles = scatterPlotGroup.append('g')
          .selectAll(".myCircles")
          .data(data)
          .join("circle")
          .attr("class", "myCircles")
          .attr("cx", d => x(d.lifeExp))
          .attr("cy", d => y(d.gdpPercap))
          .attr("r", originalCircleSize)
          .style("fill", d => continentColor(d.continent));

      scatterPlotGroup.append("g")
          .attr("transform", `translate(0, ${maxHeight})`)
          .call(d3.axisBottom(x));

      scatterPlotGroup.append("g")
          .call(d3.axisLeft(y));

  }

  function step2Highlight() {
      d3.selectAll(".myCircles")
          .style("opacity", d => d.continent === "Asia" ? 1 : 0.1)

  }

  function step3Highlight() {
      d3.selectAll(".myCircles")
          .style("opacity", d => d.continent === "Africa" ? 1 : 0.1)

  }

  function step4Highlight() {
      d3.selectAll(".myCircles")
          .style("opacity", d => d.continent === "Europe" ? 1 : 0.1)

  }

  storyReady = true;
  handleStepEnter({ index: 0, direction: "down" });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 66

Completed from the supplied instructor solution. Scroll inside the result, or expand it; the story works in both directions.

16Force-layout story

JavaScript
async function build() {
  let activeStep = 0;
  let storyReady = false;

  let numNodes = 100;
  let nodes = d3.range(numNodes).map(() => ({
      radius: Math.random() * 15 + 10,
      category: Math.floor(Math.random() * 3)
  }));

  const colorArray = ['#d9f9f4', '#9cd9de', '#86c1d4'];

  let main = d3.select("main");
  let scrolly = main.select("#scrolly");
  let svg = scrolly.select("svg");
  let article = scrolly.select("article");
  let step = article.selectAll(".step");

  let scroller = scrollama();

  let svgWidth = 1000;
  let svgHeight = 800;
  let centerX = svgWidth / 2;
  let centerY = svgHeight / 2;

  function handleResize() {
      let stepH = Math.floor(window.innerHeight * 0.75);
      step.style("height", `${stepH}px`);

      svgWidth = 1000;
      svgHeight = 800;
      centerX = svgWidth / 2;
      centerY = svgHeight / 2;

      svg
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .style("top", "0px")
          .attr("viewBox", "0 0 1000 800");

      svg.select('.scatterGroup')
          .attr('transform', `translate(${centerX}, ${centerY})`);

      scroller.resize();
      if (storyReady) handleStepEnter({ index: activeStep, direction: "down" });
  }

  function handleStepEnter(response) {
      activeStep = response.index;

      step.classed("is-active", (d, i) => i === response.index);

      switch (response.index) {
          case 0:
              createCircles();
              break;
          case 1:
              updateCircles();
              break;
          case 2:
              updateCircles1();
              break;
          case 3:
              updateCircles2();
              break;
          default:
              break;
      }
  }

  function init() {
      handleResize();

      // Ensure scatterGroup is created and centered
      svg.selectAll('.scatterGroup').remove();
      svg.append('g')
          .attr('class', 'scatterGroup')
          .attr('transform', `translate(${centerX}, ${centerY})`);

      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.33,
          })
          .onStepEnter(handleStepEnter);

      window.addEventListener('resize', handleResize);
  }

  init();

  let simulation = null;

  function stopSimulation() {
      if (simulation) simulation.stop();
      svg.selectAll("rect").interrupt();
  }

  function createCircles() {
      stopSimulation();

      const spacing = 0;
      const xCenter = [0, 0, 0].map(x => x + centerX);

      simulation = d3.forceSimulation(nodes)
          .force('charge', d3.forceManyBody().strength(20))
          .force('center', d3.forceCenter(centerX, centerY))
          .force('collision', d3.forceCollide().radius(d => d.radius))
          .force('x', d3.forceX(d => xCenter[d.category]).strength(0.1))
          .force('y', d3.forceY(centerY).strength(0.1))
          .on('tick', ticked);
  }

  function updateCircles() {
      stopSimulation();

      const spacing = 300;
      const xCenter = [-spacing, 0, spacing].map(x => x + centerX);

      simulation = d3.forceSimulation(nodes)
          .force('charge', d3.forceManyBody().strength(20))
          .force('center', d3.forceCenter(centerX, centerY))
          .force('collision', d3.forceCollide().radius(d => d.radius))
          .force('x', d3.forceX(d => xCenter[d.category]).strength(0.1))
          .force('y', d3.forceY(centerY).strength(0.1))
          .on('tick', ticked);
  }

  function updateCircles1() {
      stopSimulation();

      const spacing = 300;
      const xCenter = [-spacing, 0, spacing].map(x => x + centerX);
      const yCenterArr = [-spacing, 0, spacing].map(y => y + centerY);

      simulation = d3.forceSimulation(nodes)
          .force('charge', d3.forceManyBody().strength(20))
          .force('center', d3.forceCenter(centerX, centerY))
          .force('collision', d3.forceCollide().radius(d => d.radius))
          .force('x', d3.forceX(d => xCenter[d.category]).strength(0.1))
          .force('y', d3.forceY(d => yCenterArr[d.category]).strength(0.1))
          .on('tick', ticked);
  }

  function updateCircles2() {
      stopSimulation();

      const barWidth = 100;
      const spacing = 300;
      const xCenters = [-spacing, 0, spacing].map(x => x + centerX);

      // Group nodes by their category
      const grouped = [[], [], []];
      nodes.forEach(d => grouped[d.category].push(d));

      // Sort each group by radius and calculate positions for bar chart layout
      grouped.forEach((group, i) => {
          group.sort((a, b) => b.radius - a.radius); // Sort descending by radius

          let yOffset = centerY + 350; // Start stacking from the bottom
          group.forEach(d => {
              d.x = xCenters[i]; // Set x position based on group
              d.y = yOffset - d.radius; // Set y position for stacking
              d.height = d.radius; // Use radius as the height of the bar
              yOffset -= d.height; // Update yOffset for the next bar
          });
      });

      const group = d3.select('.scatterGroup'); // Select the scatter group for rendering

      // Bind data and update rectangles to represent the bar chart
      group.selectAll('rect')
          .data(nodes)
          .join('rect')
          .transition()
          .duration(2000)
          .attr('x', d => d.x - barWidth / 2 - centerX)
          .attr('y', d => d.y - centerY)
          .attr('width', barWidth)
          .attr('height', d => d.height)
          .attr('rx', 0) // Remove rounded corners for a rectangular shape
          .attr('ry', 0)
          .style('fill', d => colorArray[d.category])
          .style('stroke', '#fff')
          .style('fill-opacity', 1)
          .style('stroke-width', 1);

  }

  function ticked() {
      const group = d3.select('.scatterGroup');

      group.selectAll('rect')
          .data(nodes)
          .join('rect')
          .attr('x', d => d.x - d.radius - centerX)
          .attr('y', d => d.y - d.radius - centerY)
          .attr('width', d => d.radius * 2)
          .attr('height', d => d.radius * 2)
          .attr('rx', d => d.radius) // use rounded corners to make rectangle look like a circle
          .attr('ry', d => d.radius)
          .style('fill', d => colorArray[d.category])
          .style('stroke', '#fff')
          .style('fill-opacity', 0.9)
          .style('stroke-width', 1);
  }

  storyReady = true;
  handleStepEnter({ index: 0, direction: "down" });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 67–73

Based on the supplied student-lab tutorial. Scroll inside the result, or expand it; the story works in both directions.

17Scatterplot to stacked bars solution

JavaScript
async function build() {
  let activeStep = 0;
  let storyReady = false;

  let main = d3.select("main");
  let scrolly = main.select("#scrolly");
  let svg = scrolly.select("svg");
  let article = scrolly.select("article");
  let step = article.selectAll(".step");

  const margin = { top: 40, right: 150, bottom: 60, left: 100 };
  let svgWidth = 1000;
  let width = svgWidth - margin.left - margin.right;
  let height = 500;

  let scroller = scrollama();
  let data;

  let xAxisGroup, yAxisGroup;
  let xScatterScale, yScatterScale;
  let isBarChart = false;

  const continentColor = d3.scaleOrdinal()
      .domain(["Asia", "Africa", "Europe", "Americas", "Oceania"])
      .range(["#f94144", "#f3722c", "#f9c74f", "#43aa8b", "#577590"]);

  await d3.csv("datasets/countries.csv").then(function (d) {
      data = d.map(d => ({
          ...d,
          lifeExp: +d.lifeExp,
          gdpPercap: +d.gdpPercap
      }));
      init();
  });

  function init() {
      handleResize();

      svg.selectAll('.scatterGroup').remove();
      svg.append('g')
          .attr('class', 'scatterGroup')
          .attr('transform', `translate(${margin.left},${margin.top})`);

      scroller
          .setup({
              step: "#scrolly article .step",
              offset: 0.33,
              debug: false
          })
          .onStepEnter(handleStepEnter)
          // .onStepExit(handleStepExit);

      window.addEventListener('resize', handleResize);
  }

  function handleResize() {
      let stepH = Math.floor(window.innerHeight * 0.75);
      step.style("height", stepH + "px");

      svgWidth = 1000;
      width = svgWidth - margin.left - margin.right;
      let svgHeight = height + margin.top + margin.bottom;

      svg
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .attr("viewBox", "0 0 " + svgWidth + " " + svgHeight);

      scroller.resize();
      if (storyReady) handleStepEnter({ index: activeStep, direction: "down" });
  }

  function handleStepEnter(response) {
      activeStep = response.index;
      step.classed("is-active", (d, i) => i === response.index);

      switch (response.index) {
          case 0:
              createScatter();
              break;
          case 1:
              highlightContinent("Asia");
              break;
          case 2:
              highlightContinent("Africa");
              break;
          case 3:
              highlightContinent("Europe");
              break;
          case 4:
              transitionToBarChart();
              break;
      }
  }

  function createScatter() {
      const group = d3.select('.scatterGroup');
      const circleRadius = 6;

      let xMax = d3.max(data, d => d.lifeExp);
      let yMax = d3.max(data, d => d.gdpPercap);

      xScatterScale = d3.scaleLinear()
          .domain([0, xMax]).nice()
          .range([0, width]);

      yScatterScale = d3.scaleLinear()
          .domain([0, yMax]).nice()
          .range([height, 0]);

      group.selectAll(".myCircles")
          .data(data)
          .join("rect")
          .attr("class", "myCircles")
          .style("opacity", 0.9)
          .transition("layout")
          .duration(1000)
          .attr("x", d => xScatterScale(d.lifeExp) - circleRadius)
          .attr("y", d => yScatterScale(d.gdpPercap) - circleRadius)
          .attr("width", circleRadius * 2)
          .attr("height", circleRadius * 2)
          .attr("rx", circleRadius)
          .attr("ry", circleRadius)
          .style("fill", d => continentColor(d.continent));

      // Axes
      if (!xAxisGroup) {
          xAxisGroup = group.append("g").attr("class", "x-axis");
          yAxisGroup = group.append("g").attr("class", "y-axis");
      }

      xAxisGroup
          .attr("transform", `translate(0, ${height})`)
          .transition("layout")
          .duration(1000)
          .call(d3.axisBottom(xScatterScale));

      yAxisGroup
          .attr("transform", `translate(0, 0)`)
          .transition("layout")
          .duration(1000)
          .call(d3.axisLeft(yScatterScale));

      isBarChart = false;
  }

  function highlightContinent(name) {
      if (isBarChart) {
          createScatter();
      }

      d3.selectAll(".myCircles")
          .transition("focus")
          .duration(500)
          .style("opacity", d => d.continent === name ? 1 : 0.1);

  }

  function transitionToBarChart() {
      const group = d3.select('.scatterGroup');
      const barWidth = 40;
      group.selectAll(".myCircles").interrupt("focus");

      const continentMap = d3.group(data, d => d.continent);
      const continents = Array.from(continentMap.keys());

      const xBand = d3.scaleBand()
          .domain(continents)
          .range([0, width])
          .padding(0.3);

      const yStack = d3.scaleLinear()
          .domain([0, d3.max(continentMap, ([, v]) => v.length)])
          .range([0, height]);

      const yReverse = d3.scaleLinear()
          .domain([0, d3.max(continentMap, ([, v]) => v.length)])
          .range([height, 0]);

      let yOffsetMap = new Map(continents.map(c => [c, 0]));

      data.forEach(d => {
          const offset = yOffsetMap.get(d.continent);
          d._barX = xBand(d.continent);
          d._barY = height - yStack(1) - offset;
          d._barHeight = yStack(1);
          yOffsetMap.set(d.continent, offset + yStack(1));
      });

      group.selectAll(".myCircles")
          .data(data)
          .transition("layout")
          .duration(1000)
          .attr("x", d => d._barX + (xBand.bandwidth() - barWidth) / 2)
          .attr("y", d => d._barY)
          .attr("width", barWidth)
          .attr("height", d => d._barHeight)
          .attr("rx", 0)
          .attr("ry", 0)
          .style("opacity", 1);

      // Update x-axis
      xAxisGroup
          .transition("layout")
          .duration(1000)
          .call(d3.axisBottom(xBand));

      // Update y-axis for bar chart
      yAxisGroup
          .transition("layout")
          .duration(1000)
          .call(d3.axisLeft(yReverse));

      isBarChart = true;
  }

  storyReady = true;
  handleStepEnter({ index: 0, direction: "down" });
}

build();
Result
Loading…
Data & source

Lecture 24, slides 74

Completed from the supplied instructor solution. Scroll inside the result, or expand it; the story works in both directions.