D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
matthieuMoisson
Full window
Github gist
TP3_dataviz_Stacked
Built with
blockbuilder.org
<!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; } svg { font: 10px sans-serif; } .line { fill: none; stroke: black; stroke-width: 2px; } </style> </head> <body> <script> var margin = {top: 20, right: 30, bottom: 20, left: 100}, width = 760 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; var svg = d3.select("body").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 + ")"); var parseDate = d3.timeParse("%b %Y"); var x = d3.scaleTime().range([0, width]), y = d3.scaleLinear().range([height, 0]), c = d3.scaleOrdinal(d3.schemeCategory10); var area = d3.area() .curve(d3.curveBasis) .x(function(d) { return x(d.date); }) .y0(function(d) { return y(d.beforePrice); }) .y1(function(d) { return y(d.somePrice); }); var line = d3.line() .curve(d3.curveBasis) .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.price); }); d3.text('dataset.csv', function(error, raw) { var dsv = d3.dsvFormat(',') var data = dsv.parse(raw); // Nest stock values by symbol. var symbols = d3.nest() .key(function(d) { return d.symbol; }) .entries(data); // Parse and caculate some values for each symbols var i = 0; var sumMaxPrice = 0; symbols.forEach(function(s) { s.values.forEach(function(d) { d.date = parseDate(d.date); d.price = +d.price; }); // Pour faire pointer un element sur le suivant var j = 0; s.values.forEach(function(v){ if(i == 0){ // pas de petit frere v.beforePrice = 0; }else{ v.beforePrice = symbols[i-1].values[j].somePrice; } v.somePrice = v.beforePrice + v.price; j++; }); i++; s.maxPrice = d3.max(s.values, function(d) { return d.somePrice; }); s.sumPrice = d3.sum(s.values, function(d) { return d.price; }); s.lastPrice = s.values[s.values.length - 1].somePrice; console.log(s.lastPrice); s.someLastPrice = s.values[s.values.length - 1].somePrice; }); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(symbols.map(function(d) { return d.maxPrice; }))]) svg.selectAll(".line").data(symbols).enter() .append("path") .attr("fill", function(d) { return c(d.key); }) .attr("d", function(d) { return area(d.values); }) .style("fill-opacity", 0.5)// Opacity du remplissage .style("stroke", "black" ) .style("stroke-opacity", 1); // Opacity du trait; svg.selectAll() .data(symbols) .enter().append("text") .attr("x", width + 30) .attr("y", function(d) { return height - d.lastPrice/2 }) .style("text-anchor", "end") .text(function(d) { return d.key }); }); </script> </body>
https://d3js.org/d3.v4.min.js