Skip to content

Instantly share code, notes, and snippets.

@robert-moore
Last active August 25, 2015 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robert-moore/97b2fc0d8687462fe129 to your computer and use it in GitHub Desktop.
Save robert-moore/97b2fc0d8687462fe129 to your computer and use it in GitHub Desktop.
Simple D3.js Bar Chart Generation

A simple generator function for a D3.js bar graph with an options parameter.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updatable Charts (2 of 4)</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body {
padding: 20px 0 0 10px;
}
</style>
</head>
<body>
<div id="weatherHistory"></div>
<br>
<div id="runningHistory"></div>
<script>
var milesRun = [2, 5, 4, 1, 2, 6, 5];
var highTemperatures = [77, 71, 82, 87, 84, 78, 80, 84, 86, 72, 71, 68, 75, 73, 80, 85, 86, 80];
function drawChart(dom, data, options) {
var width = options.width || 800;
var height = options.height || 200;
var barPadding = options.barPadding || 1;
var fillColor = options.fillColor || 'steelblue';
var barSpacing = height / data.length;
var barHeight = barSpacing - barPadding;
var maxValue = d3.max(data);
var widthScale = width / maxValue;
d3.select(dom).append('svg')
.attr('height', height)
.attr('width', width)
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('y', function (d, i) { return i * barSpacing })
.attr('height', barHeight)
.attr('x', 0)
.attr('width', function (d) { return d*widthScale})
.style('fill', fillColor);
}
var weatherOptions = {fillColor: 'coral'};
drawChart('#weatherHistory', highTemperatures, weatherOptions);
var runningOptions = {barPadding: 2};
drawChart('#runningHistory', milesRun, runningOptions);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment