Creating Bar Charts with SVG
You'll learn how to transform data arrays into visual bar charts using SVG <rect> elements with calculated positioning.
The Core Idea
A bar chart is simply a series of rectangles whose dimensions reflect your data values. Each data point becomes one <rect> element where the height (for vertical bars) or width (for horizontal bars) corresponds to the value, and positioning ensures bars don't overlap.
Think of it like arranging books on a shelf: each book's height represents its page count, and you space them evenly so each book has its own spot.
Vertical Bar Chart Approach
For vertical bars growing upward, you'll map each data value to:
- x position:
index × barWidth + spacing - y position:
chartHeight - (value × scale)(SVG's origin is top-left, so you flip it) - width: fixed bar width
- height:
value × scale
<svg width="400" height="300">
<!-- Data: [50, 80, 30, 100] -->
<rect x="10" y="250" width="80" height="50" fill="steelblue" />
<rect x="100" y="220" width="80" height="80" fill="steelblue" />
<rect x="190" y="270" width="80" height="30" fill="steelblue" />
<rect x="280" y="200" width="80" height="100" fill="steelblue" />
</svg>
Horizontal Bar Chart Approach
For horizontal bars, swap the logic:
- x: always starts at 0 (or margin)
- y:
index × barHeight + spacing - width:
value × scale - height: fixed bar height
The key skill is calculating scales (maxValue / availableSpace) and spacing to ensure your data fits within the SVG viewport without clipping.
Key Takeaway: Bar charts use <rect> elements with data-driven x/y positions and width/height values, requiring coordinate calculations that account for SVG's top-left origin and proper scaling to fit your viewport.