Built with blockbuilder.org
Created
December 28, 2018 04:56
-
-
Save jwilber/fb5917b3b31e54f5bc07758cccf2657d to your computer and use it in GitHub Desktop.
reusable barchart: 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> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.js"></script> | |
<style> | |
svg { | |
border: 1px dotted red; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="runningHistory"></div> | |
<div id="weatherHistory"></div> | |
</body> | |
<script> | |
function barChart() { | |
// attributes accessible by caller | |
let width = 500; | |
let height = 400; | |
let barPadding = 5; | |
let fillColor = 'coral'; | |
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', (d,i) => i * barSpacing) | |
.attr('height', barHeight) | |
.attr('x', 0) | |
.attr('width', d => 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(10).fillColor('red'); | |
d3.select('#runningHistory') | |
.datum(milesRun) | |
.call(runningChart); | |
var weatherChart = barChart().fillColor('coral'); | |
d3.select('#weatherHistory') | |
.datum(highTemperatures) | |
.call(weatherChart); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment