liveBook · Manning

Transform attribute

As explained in D3.js in Action, Third Edition

The SVG transform attribute specifies geometric transformations such as translation, rotation, scaling, or skewing for an element and its descendants.

The SVG transform attribute repositions a group and its descendants together. A translated group acts like a movable container: children use coordinates relative to that group rather than the whole SVG. section 3.5

For a horizontal bar chart, bind each datum to a g element and translate it vertically with translate(0, yScale(d.technology)). Rectangles and text inside every group then share the bar’s vertical position while keeping simple local coordinates. section 3.5

Position donut charts by year

Translate each donut’s group horizontally with a band scale and vertically to half the inner chart height. Each set of arcs can then be drawn around its own translated origin. section 5.1.1

Listing 14.4 Adding a responsive grid (Grid.svelte)
{#if svgWidth && svgHeight}
  <svg width={svgWidth} height={svgHeight}>
    {#each years as year, i}                                   #1
      <g transform="translate(                                 #2
        {(i % numColumns) * smWidth},                           
        {Math.floor(i / numColumns) * smHeight})"               
      >                                                       
        <rect x={0} y={0} width={smWidth}     #3
          height={smHeight} />              
      </g>
    {/each}
  </svg>
{/if}

<style>
  svg {
    border: 1px solid magenta;
  }
  rect {
    fill: none;
    stroke: cyan;
  }
</style>

A responsive grid translates each small-multiple group into its calculated column and row. Modulo selects the column; the index divided by the column count selects the row. section 14.4.2

How D3.js in Action, Third Edition covers it

How deep it goes
Works through translate() with scale- and index-derived coordinates, without covering other transform operations.
Examples
Demonstrates labeled horizontal bars, year-based donut charts, and a responsive small-multiple grid.
What you can do after
Build SVG layouts by translating groups from data scales or calculated grid positions.
How it connects
Connects SVG groups with data binding, D3 scales, band scales, and responsive grids.

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.