Course contentsShow
← Web Development
Lesson 2604 of 2,98247. Data VisualizationFree lesson

SVG Groups and Transforms

Use <g> elements and transform attributes (translate, scale, rotate) to position chart elements.

SVG Groups and Transforms

What you'll learn: How to organize and position SVG chart elements efficiently using the <g> element and transform attributes.

Understanding SVG Groups

Think of the <g> (group) element as a folder for your SVG shapes. Just as you'd group files together in a folder to organize and move them as one unit, <g> lets you bundle multiple SVG elements and apply transformations to the entire collection at once.

<svg width="400" height="300">
  <g id="bar-chart">
    <rect x="0" y="0" width="50" height="100" fill="blue"/>
    <rect x="60" y="0" width="50" height="150" fill="blue"/>
  </g>
</svg>

Transform Attributes

The transform attribute lets you reposition, resize, and rotate your grouped elements without changing their original coordinates—like moving a physical blueprint around without redrawing it.

translate - Moving Elements

Shifts elements by x and y amounts:

<g transform="translate(100, 50)">
  <circle cx="0" cy="0" r="20" fill="red"/>
</g>

scale - Resizing Elements

Changes size proportionally:

<g transform="scale(2)">
  <!-- Everything inside is 2x larger -->
  <rect x="0" y="0" width="50" height="50"/>
</g>

rotate - Spinning Elements

Rotates around a point (default is origin):

<g transform="rotate(45, 100, 100)">
  <text x="100" y="100">Angled Label</text>
</g>

Combining Transforms

Chain multiple transforms with spaces:

<g transform="translate(150, 100) scale(0.5) rotate(30)">
  <!-- Moved, shrunk, then rotated -->
</g>

Practical Use in Charts

Groups with transforms are essential for data visualization: position your y-axis, offset bar groups, create chart margins, or flip coordinate systems (since SVG's y-axis points downward).

Key Takeaway: Use <g> elements to organize related chart components and transform attributes (translate, scale, rotate) to position them efficiently without recalculating individual element coordinates.