Skip to content

Instantly share code, notes, and snippets.

@codementum
Created September 30, 2016 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codementum/2ee76715d716e59efab283ce915de740 to your computer and use it in GitHub Desktop.
Save codementum/2ee76715d716e59efab283ce915de740 to your computer and use it in GitHub Desktop.
Streamgraph
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var data = [
{month: new Date(2015, 0, 1), apples: 3840, bananas: 1920, cherries: 960, dates: 400},
{month: new Date(2015, 1, 1), apples: 1600, bananas: 1440, cherries: 960, dates: 400},
{month: new Date(2015, 2, 1), apples: 34, bananas: 60, cherries: 640, dates: 400},
{month: new Date(2015, 3, 1), apples: 320, bananas: 480, cherries: 640, dates: 400},
{month: new Date(2015, 4, 1), apples: 500, bananas: 23, cherries: 100, dates: 50},
{month: new Date(2015, 5, 1), apples: 1600, bananas: 1440, cherries: 960, dates: 400},
{month: new Date(2015, 6, 1), apples: 1200, bananas: 1000, cherries: 800, dates: 700},
{month: new Date(2015, 7, 1), apples: 320, bananas: 1000, cherries: 640, dates: 700},
{month: new Date(2015, 8, 1), apples: 1200, bananas: 1000, cherries: 800, dates: 400},
{month: new Date(2015, 9, 1), apples: 34, bananas: 1000, cherries: 640, dates: 1000},
{month: new Date(2015, 10, 1), apples: 3840, bananas: 1000, cherries: 800, dates: 700},
{month: new Date(2015, 11, 1), apples: 1200, bananas: 480, cherries: 100, dates: 2000},
];
var stack = d3.stack()
.keys(["apples", "bananas", "cherries", "dates"])
.order(d3.stackOrderNone)
.offset(d3.stackOffsetWiggle);
var series = stack(data);
var width = 600,
height = 500;
var x = d3.scaleTime()
.domain(d3.extent(data, function(d){ return d.month; }))
.range([0, width]);
// setup axis
var xAxis = d3.axisBottom(x);
var y = d3.scaleLinear()
.domain([0, d3.max(series, function(layer) { return d3.max(layer, function(d){ return d[0] + d[1];}); })])
.range([height, 0]);
var color = d3.scaleLinear()
.range(["#51D0D7", "#31B5BB"]);
var area = d3.area()
.x(function(d) { console.info('in area function', d); return x(d.data.month); })
.y0(function(d) { return y(d[0]); })
.y1(function(d) { return y(d[1]); })
.curve(d3.curveBasis);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("path")
.data(series)
.enter().append("path")
.attr("d", area)
.style("fill", function() { return color(Math.random()); });
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment