This is the code for Chapter 5, Figure 21 from D3.js in Action showing how to use d3.layout.stack() to create a streamgraph.
<html>
<head>
<title>D3 in Action Chapter 5 - Example 9</title>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<style>
svg {
height: 500px;
width: 500px;
border: 1px solid gray;
}
</style>
<body>
<div id="viz">
<svg>
</svg>
</div>
</body>
<footer>
<script>
d3.csv("movies.csv", function(error,data) {dataViz(data)});
function dataViz(incData) {
expData = incData;
stackData = [];
var xScale = d3.scale.linear()
.domain([0, 10])
.range([0, 500]);
var yScale = d3.scale.linear()
.domain([0, 100])
.range([500, 0]);
var movieColors = d3.scale.category10(["movie1","movie2","movie3","movie4","movie5","movie6"]);
var stackArea = d3.svg.area()
.interpolate("basis")
.x(function(d) { return xScale(d.x); })
.y0(function(d) { return yScale(d.y0); })
.y1(function(d) { return yScale(d.y0 + d.y); });
for (x in incData[0]) {
if (x != "day") {
var newMovieObject = {name: x, values: []};
for (y in incData) {
newMovieObject.values.push({x: parseInt(incData[y]["day"]) ,y: parseInt(incData[y][x])})
}
stackData.push(newMovieObject);
}
}
stackLayout = d3.layout.stack()
.offset("silhouette")
.order("inside-out")
.values(function(d) { return d.values; });
d3.select("svg").selectAll("path")
.data(stackLayout(stackData))
.enter().append("path")
.style("fill", function(d) {return movieColors(d.name)})
.attr("d", function(d) { return stackArea(d.values); })
}
</script>
</footer>
</html>
day,movie1,movie2,movie3,movie4,movie5,movie6
1,20,8,3,0,0,0
2,18,5,1,13,0,0
3,14,3,1,10,0,0
4,7,3,0,5,27,15
5,4,3,0,2,20,14
6,3,1,0,0,10,13
7,2,0,0,0,8,12
8,0,0,0,0,6,11
9,0,0,0,0,3,9
10,0,0,0,0,1,8