Skip to content

Instantly share code, notes, and snippets.

@robert-moore
Last active September 6, 2015 20:10
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/c390811d851a390d20e9 to your computer and use it in GitHub Desktop.
Save robert-moore/c390811d851a390d20e9 to your computer and use it in GitHub Desktop.
D3.js Bar Chart with configuration variables

A simple D3.js bar chart with some of the configuration variables abstracted out for quick and easy changes. The bar chart will scale based on the length and values of the data.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updatable Charts (1 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>
<script>
var highTemperatures = [77, 71, 82, 87, 84, 78, 80, 84, 86, 72, 71, 68];
var height = 300;
var width = 800;
var barPadding = 1;
var barSpacing = height / highTemperatures.length;
var barHeight = barSpacing - barPadding;
var maxValue = d3.max(highTemperatures);
var widthScale = width / maxValue;
d3.select('body').append('svg')
.attr('height', height)
.attr('width', width)
.selectAll('rect')
.data(highTemperatures)
.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', 'steelblue');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment