nick34992
2/27/2017 - 12:47 AM

D3: Bar Graph with Margin

D3: Bar Graph with Margin

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
<head>
    <script src="https://d3js.org/d3.v4.js"></script>
    <meta name="description"
          content="Afghan Opium Poppy Production, 1994 to 2015,
                   1 unit = 1000 hectares" />
</head>
<body>
    <script>
        /* Data Source: United Nations Office on Drugs and Crime (Kabul) */
        var data = [71, 54, 57, 58, 64, 91, 82, 8, 74, 80, 131, 104, 165,
                    193, 157, 123, 123, 131, 154, 209, 224, 183];
        var barWidth = 30, barPadding = 2;
        var maxValue = d3.max(data);
        var graphWidth = data.length * (barWidth + barPadding) - barPadding;
        var margin = { top: 10, right: 10, bottom: 10, left: 50 };
        var totalWidth = graphWidth + margin.left + margin.right;
        var totalHeight = maxValue + margin.top + margin.bottom;
        var svg = d3.select("body")
                    .append("svg")
                    .attr("width", totalWidth)
                    .attr("height", totalHeight);
        svg.append("rect")
           .attr("width", totalWidth)
           .attr("height", totalHeight)
           .attr("fill", "white")
           .attr("stroke", "black")
           .attr("stroke-width", 1);
        var graphGroup = svg.append("g")
                  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        graphGroup.append("rect")
                  .attr("fill", "rgba(0,0,0,0.1)")
                  .attr("width", totalWidth - (margin.left + margin.right))
                  .attr("height", totalHeight - (margin.bottom + margin.top));
        function xloc(d, i) { return i * (barWidth + barPadding); }
        function yloc(d) {return maxValue - d;}
        function translator(d, i) {return "translate(" + xloc(d, i) + "," + yloc(d) + ")";}
        var barGroup = graphGroup.selectAll("g")
                                 .data(data)
                                 .enter()
                                 .append("g")
                                 .attr("transform", translator);
        barGroup.append("rect")
                .attr("fill", "steelblue")
                .attr("width", barWidth)
                .attr("height", function (d) { return d; });
        var textTranslator = "translate(" + barWidth / 2 + ",0)";
        barGroup.append("text")
                .text(function(d) { return d; })
                .attr("fill", "white")
                .attr("alignment-baseline", "before-edge")
                .attr("text-anchor", "middle")
                .attr("transform", textTranslator)
                .style("font", "10px sans-serif");
    </script>
</body>
</html>