D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Ctuauden
Full window
Github gist
Stocks Bar chart
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; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var margin= {top: 20, bottom: 20, left: 40, right: 40} height = 500 - margin.bottom - margin.top, width = 960 - margin.right - margin.bottom; var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); var y = d3.scaleLinear() .range([0, height/3]); // ordinal var x = d3.scaleBand() .range([0, width]); var color = d3.scaleOrdinal().range(["#ff1111","#f3ff0f","#0fdbff","#0600d1"]); var ChartType = 'stacked'; // lecture du csv d3.csv("stocks.csv",function(data) { data.forEach(function(d){ d.symbol = d.symbol; d.date = d3.timeParse("%b %Y")(d.date); d.month = d3.timeFormat("%b")(d.date); d.year = d3.timeFormat("%Y")(d.date); //console.log(d.year) d.price = +d.price; }) var mes_donnees = d3.nest() .key(function(d){return d.year;}) .key(function(d){return d.symbol;}) .rollup(function(d) { return d3.mean(d, function(d) { return d.price; }); }) .entries(data) d3.selectAll("body").on("click",function(){ if(ChartType==="stacked"){ChartType = "grouped",DessinerGraphique(mes_donnees,ChartType);} else{ChartType="stacked",DessinerGraphique(mes_donnees,ChartType);} }); function DessinerGraphique(data,type){ if (type==="stacked"){ console.log("stacké") d3.selectAll("circle").remove() x.domain([2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010]); y.domain([0, d3.max(data,sum(function(d){return d.price;}))]); svg.append("g").selectAll("g") .data(d3.stack(data).keys([2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010])) .enter() .append("g") .style("fill",function(d){return color(d.symbol)}) .selectAll("rect") .data(function(d){console.log(d);}) .enter() .append("rect") .attr("x", function(d,i){return x(i)}) .attr("y", function(d){console.log(d) ;}) .attr("height", 20) .attr("width", 20) } if (type==="grouped"){ console.log("groupé") d3.selectAll("rect").remove() //x.domain([2000,d3.max(data,function(d){return d.year;})]); x.domain([2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010]); y.domain([0, d3.max(data,function(d){return d.price;})]); svg.selectAll("body") .data(data) .enter() .append("circle") .attr("cx", function(d, i) { return x(i); }) .attr("cy", function(d, i) { return y(d); }) .style("fill",function(d){return color(d.symbol)}) .attr("r",10); } } }) // fin de lecture du csv </script> </body>
https://d3js.org/d3.v4.min.js