Built with blockbuilder.org
Last active
December 31, 2018 05:32
-
-
Save jwilber/ed0065c8748ae07e56e173d954a7d8b4 to your computer and use it in GitHub Desktop.
reusable bar: bostock style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
</style> | |
</head> | |
<body> | |
<div id="weatherHistory"></div> | |
<div id="runningHistory"</div> | |
<script> | |
// Using Mike Bostock's Towards Reusable Charts Pattern | |
function barChart() { | |
// All options that should be accessible to caller | |
var width = 900; | |
var height = 200; | |
var barPadding = 1; | |
var fillColor = 'steelblue'; | |
function chart(selection){ | |
selection.each(function (data) { | |
var barSpacing = height / data.length; | |
var barHeight = barSpacing - barPadding; | |
var maxValue = d3.max(data); | |
var widthScale = width / maxValue; | |
d3.select(this).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); | |
}); | |
} | |
chart.width = function(value) { | |
if (!arguments.length) return margin; | |
width = value; | |
return chart; | |
}; | |
chart.height = function(value) { | |
if (!arguments.length) return height; | |
height = value; | |
return chart; | |
}; | |
chart.barPadding = function(value) { | |
if (!arguments.length) return barPadding; | |
barPadding = value; | |
return chart; | |
}; | |
chart.fillColor = function(value) { | |
if (!arguments.length) return fillColor; | |
fillColor = value; | |
return chart; | |
}; | |
return chart; | |
} | |
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]; | |
var runningChart = barChart().barPadding(2); | |
d3.select('#runningHistory') | |
.datum(milesRun) | |
.call(runningChart); | |
var weatherChart = barChart().fillColor('coral'); | |
d3.select('#weatherHistory') | |
.datum(highTemperatures) | |
.call(weatherChart); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment