Skip to content

Instantly share code, notes, and snippets.

@jackross
Forked from anotherjavadude/index.html
Created February 13, 2014 16:53
Show Gist options
  • Save jackross/8978999 to your computer and use it in GitHub Desktop.
Save jackross/8978999 to your computer and use it in GitHub Desktop.

Starting from Mike's sample (https://gist.github.com/1134768) I stripped down the chart to the bare minimum to understand the physics. I use a matrix instead of a csv or json. With the console.log outputs you can look at the transformation of the matrix when fed into the stack layout.

<!DOCTYPE html>
<html>
<head>
<title>Simple Stack</title>
<script src="http://d3js.org/d3.v3.js"></script>
<style>
svg {
border: solid 1px #ccc;
font: 10px sans-serif;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<div id="viz"></div>
<script type="text/javascript">
var w = 960,
h = 500
// create canvas
var svg = d3.select("#viz").append("svg:svg")
.attr("class", "chart")
.attr("width", w)
.attr("height", h )
.append("svg:g")
.attr("transform", "translate(10,470)");
x = d3.scale.ordinal().rangeRoundBands([0, w-50])
y = d3.scale.linear().range([0, h-50])
z = d3.scale.ordinal().range(["darkblue", "blue", "lightblue"])
console.log("RAW MATRIX---------------------------");
// 4 columns: ID,c1,c2,c3
var matrix = [
[ 1, 5871, 8916, 2868],
[ 2, 10048, 2060, 6171],
[ 3, 16145, 8090, 8045],
[ 4, 990, 940, 6907],
[ 5, 450, 430, 5000]
];
console.log(matrix)
console.log("REMAP---------------------------");
var remapped =["c1","c2","c3"].map(function(dat,i){
return matrix.map(function(d,ii){
return {x: ii, y: d[i+1] };
})
});
console.log(remapped)
console.log("LAYOUT---------------------------");
var stacked = d3.layout.stack()(remapped)
console.log(stacked)
x.domain(stacked[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(stacked[stacked.length - 1], function(d) { return d.y0 + d.y; })]);
// show the domains of the scales
console.log("x.domain(): " + x.domain())
console.log("y.domain(): " + y.domain())
console.log("------------------------------------------------------------------");
// Add a group for each column.
var valgroup = svg.selectAll("g.valgroup")
.data(stacked)
.enter().append("svg:g")
.attr("class", "valgroup")
.style("fill", function(d, i) { return z(i); })
.style("stroke", function(d, i) { return d3.rgb(z(i)).darker(); });
// Add a rect for each date.
var rect = valgroup.selectAll("rect")
.data(function(d){return d;})
.enter().append("svg:rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return -y(d.y0) - y(d.y); })
.attr("height", function(d) { return y(d.y); })
.attr("width", x.rangeBand());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment