Skip to content

Instantly share code, notes, and snippets.

@bet4a
Last active November 6, 2015 10:23
Show Gist options
  • Save bet4a/691262e54d4c787118c4 to your computer and use it in GitHub Desktop.
Save bet4a/691262e54d4c787118c4 to your computer and use it in GitHub Desktop.
Movie steamgraph
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
height: 500px;
width: 500px;
border: 1px solid gray;
}
line {
shape-rendering: crispEdges;
stroke: #000000;
}
path.domain {
stroke: #000;
stroke-width: 1;
fill: none;
}
path.movie {
stroke: none;
}
</style>
<svg></svg>
<script src="//d3js.org/d3.v3.js"></script>
<script src="//d3js.org/colorbrewer.v1.js"></script>
<script>
var xScale = d3.scale.linear().domain([1, 10]).range([20, 470]);
var yScale = d3.scale.linear().domain([-50, 50]).range([480, 20]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickSize(480)
.tickValues([1,2,3,4,5,6,7,8,9,10]);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("right")
.ticks(4)
.tickSize(470);
d3.select("svg").append("g").attr("id", "xAxisG").call(xAxis);
d3.select("svg").append("g").attr("id", "yAxisG").call(yAxis);
var fillScale = colorbrewer.Set1[6];
var n = 0;
d3.csv('movies.csv', function(data) {
for (x in data[0]) {
if (x !== "day") {
var movieArea = d3.svg.area()
.x(function(d) {
return xScale(d.day)
})
.y(function(d) {
return yScale(alternateStacking(d, x, "top"));
})
.y0(function(d) {
return yScale(alternateStacking(d, x, "bottom"));
})
.interpolate("basis");
d3.select("svg")
.insert("path",".movie")
.attr("class", "movie")
.style("id", x + "Area")
.attr("d", movieArea(data))
.style("fill", fillScale[n-1]);
}
n++;
}
});
function alternateStacking(incomingData, incomingAttribute, topBottom) {
var newHeight = 0;
var skip = true;
for (x in incomingData) {
if (x != "day") {
if (x == "movie1" || skip == false) {
newHeight += parseInt(incomingData[x]);
if (x === incomingAttribute) {
break;
}
if (skip == false) {
skip = true;
} else {
skip = (n%2 == 0 ? false : true);
}
} else {
skip = false;
}
}
}
if (x == "movie1") {
newHeight = newHeight * 0.5;
}
if (topBottom == "bottom") {
newHeight = newHeight * -1;
}
if (n > 1 && n%2 == 1 && topBottom == "bottom") {
newHeight = 0;
}
if (n > 1 && n%2 == 0 && topBottom == "top") {
newHeight = 0;
}
return newHeight;
}
</script>
day movie1 movie2 movie3 movie4 movie5 movie6
1 20 8 3 0 5 0
2 18 5 1 13 5 0
3 14 3 1 10 5 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment