Creating SVG Charts with D3: Build a Static Bar Chart

Learn to create static SVG bar charts using D3.js in this step-by-step tutorial. Explore essential SVG elements and transform methods for effective data visualization.



Example: Static SVG Bar Chart

Here’s a simple static bar chart using SVG elements:


<svg class="chart" width="420" height="120">
<g transform="translate(0,0)">
    <rect width="50" height="19"></rect>
    <text x="47" y="9.5" dy=".35em">5</text>
</g>
<g transform="translate(0,20)">
    <rect width="100" height="19"></rect>
    <text x="97" y="9.5" dy=".35em">10</text>
</g>
<g transform="translate(0,40)">
    <rect width="120" height="19"></rect>
    <text x="117" y="9.5" dy=".35em">12</text>
</g>
</svg>

Explanation:

  • Geometry: Use <g> elements to group bars and text, positioned with transform="translate(x, y)".
  • Styles: fill sets colors and text-anchor aligns text.

Example: Dynamic SVG Bar Chart with D3.js

Creating a bar chart dynamically with D3.js:


<script>
var data = [5, 10, 12];
var width = 200, scaleFactor = 10, barHeight = 20;

var graph = d3.select("body").append("svg")
              .attr("width", width)
              .attr("height", barHeight * data.length);

var bar = graph.selectAll("g")
              .data(data)
              .enter()
              .append("g")
              .attr("transform", function(d, i) {
                    return "translate(0," + i * barHeight + ")";
              });

bar.append("rect")
    .attr("width", function(d) { return d * scaleFactor; })
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return d * scaleFactor; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });
</script>

Explanation:

  • Data Binding: d3.select("body").append("svg") creates SVG, and data(data) binds the data array.
  • Dynamic Creation: Bars and text are added with attributes based on data values.

Example: SVG Circle Chart

Creating an SVG circle chart with D3.js:


<script>
var width = 500;
var height = 500;
var data = [10, 15, 20, 25, 30];
var colors = ['#ffffcc','#c2e699','#78c679','#31a354','#006837'];

var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height);

var g = svg.selectAll("g")
            .data(data)
            .enter()
            .append("g");

g.append("circle")
  .attr("cx", function(d, i) { return i * 100 + 50; })
  .attr("cy", 100)
  .attr("r", function(d) { return d * 1.5; })
  .attr("fill", function(d, i) { return colors[i]; });

g.append("text")
  .attr("x", function(d, i) { return i * 100 + 40; })
  .attr("y", 105)
  .text(function(d) { return d; });
</script>

Explanation:

  • Data Binding: data(data) binds the data array to <g> elements.
  • Circle Creation: Circles and text are positioned and styled based on data values.

In the next chapter, we'll explore D3 scales and how to add axes to our charts for improved data representation.