Skip to content

Instantly share code, notes, and snippets.

@areologist
Last active January 11, 2018 15:38
Show Gist options
  • Save areologist/f85b874b71688c975f092734bf72e0d4 to your computer and use it in GitHub Desktop.
Save areologist/f85b874b71688c975f092734bf72e0d4 to your computer and use it in GitHub Desktop.
stacked bar experiment 2
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.chart {
background-color: #f6fafc;
border: 1px solid #333;
}
.segment {
opacity: 0.7;
}
.segment:hover {
opacity: 1;
}
.tick text {
font-size: 10px;
}
</style>
</head>
<body>
<div class="chart"></div>
<script>
const margin = { top: 25, right: 35, bottom: 100, left: 50 };
const width = 720 - margin.left - margin.right;
const height = 450 - margin.top - margin.bottom;
const fullWidth = width + margin.left + margin.right;
const fullHeight = height + margin.top + margin.bottom;
const data = [
{subject: 'mathematics', freshman: 63, sophomore: 19, junior: 45, senior: 94},
{subject: 'geography', freshman: 82, sophomore: 8, junior: 46, senior: 60},
{subject: 'spelling', freshman: 74, sophomore: 74, junior: 74, senior: 74},
{subject: 'reading', freshman: 97, sophomore: 12, junior: 34, senior: 17},
{subject: 'science', freshman: 52, sophomore: 52, junior: 52, senior: 52}
];
const colors = ['#333', '#666', '#999', '#ccc'];
const groups = ['freshman', 'sophomore', 'junior', 'senior'];
const layout = d3.stack().keys(groups)(data);
const svg = d3.select('.chart')
.append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
const xScale = d3.scaleBand()
.padding(0.1)
.domain(data.map(d => d.subject))
.range([0, width]);
const yMax = 300;
const yScale = d3.scaleLinear()
.domain([0, yMax])
.range([height, 0]);
const yAxis = d3.axisLeft(yScale).ticks(10);
svg.append('g').call(yAxis);
const xAxis = d3.axisBottom(xScale);
svg.append('g')
.attr('transform', `translate(0, ${height})`)
.call(xAxis)
.selectAll('text')
.style('text-anchor', 'end')
.attr('transform', 'rotate(-45)');
svg
.selectAll('.group')
.data(layout)
.enter()
.append('g')
.attr('class', 'group')
.attr('name', ({key}) => key)
.attr('fill', (d, i) => colors[i])
.selectAll('.segment')
.data(d => d)
.enter()
.append('rect')
.attr('class', 'segment')
.attr('x', ({data: {subject}}) => xScale(subject))
.attr('y', ([y, h]) => yScale(h))
.attr('width', xScale.bandwidth())
.attr('height', ([y, h]) => height - yScale(h - y));
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment