Created
August 29, 2019 15:42
-
-
Save lordkebab/467867e48333a096f55c3e450ebba7d9 to your computer and use it in GitHub Desktop.
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> | |
<meta charset="utf-8"> | |
<div id="chart"></div> | |
<script> | |
const url = 'https://gist.githubusercontent.com/mbostock/5429c74d6aba68c52c7b39642c98deed/raw/50a5157a1d920191b0a7f636796ee721047cbb92/us-population-state-age.csv'; | |
const colors = ['#CACF85', '#8CBA80', '#658E9C', '#4D5382', '#514663', '#828C51', '#335145', '#071E22', '#1D7874']; | |
const svgHeight = 400; | |
const svgWidth = 1080; | |
const margins = {top: 20, bottom: 20, left: 20, right: 20}; | |
const w = svgWidth - margins.left - margins.right; | |
const h = svgHeight - margins.top - margins.bottom; | |
d3.csv(url, d3.autoType()).then((data) => { | |
var keys = data.columns.slice(1); | |
var stack = d3.stack().keys(keys); | |
var series = stack(data); | |
// scale | |
var max = d3.max(series, (d) => { | |
return d3.max(d, (d) => { | |
return d[1]; | |
}); | |
}); | |
var yScale = d3.scaleLinear() | |
.domain([0, max]) | |
.range([h,0]); | |
// build the chart | |
d3.select('#chart') | |
.append('svg') | |
.attr('width', svgWidth) | |
.attr('height', svgHeight); | |
// build each series | |
var g = d3.select('svg') | |
.selectAll('g.series') | |
.data(series) | |
.enter() | |
.append('g').classed('series', true) | |
.style('fill', (d, i) => { return colors[i] }); | |
// each rect | |
g.selectAll('rect') | |
.data( (d) => { return d } ) | |
.enter() | |
.append('rect') | |
.attr('x', (d, i) => i * 20 ) | |
.attr('y', (d, i) => { return d[1]; }) | |
.attr('width', 19) | |
.attr('height', (d, i) => { return yScale(d[0]) - yScale(d[1]) }); | |
}); | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment