Skip to content

Instantly share code, notes, and snippets.

@jeffreymorganio
Created June 12, 2016 14:50
Show Gist options
  • Save jeffreymorganio/1d723e028b612b919d6354888e4ca778 to your computer and use it in GitHub Desktop.
Save jeffreymorganio/1d723e028b612b919d6354888e4ca778 to your computer and use it in GitHub Desktop.
A D3 Bar Chart of SVG Rectangles.
license: mit

A D3 bar chart created with SVG rectangles.

function drawBarChart() {
var width = 500;
var height = 250;
var barPadding = 4;
var dataSet = randomDataSet(10, 5, 25);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("rect")
.data(dataSet)
.enter()
.append("rect")
.attr("x", function(d, i) { return i * (width / dataSet.length); })
.attr("y", function(d) { return height - d * 10; })
.attr("width", width / dataSet.length - barPadding)
.attr("height", function(d) { return d * 10; })
.attr("fill", "#3498DB");
}
function randomDataSet(dataSetSize, minValue, maxValue) {
return new Array(dataSetSize).fill(0).map(function(n) {
return Math.random() * (maxValue - minValue) + minValue;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A D3 Bar Chart of SVG Rectangles</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js" charset="utf-8"></script>
<script src="bar-chart.js"></script>
</head>
<body onload="drawBarChart()">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment