D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tblondelle
Full window
Github gist
1. Area 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; } svg { font: 10px sans-serif; } .line { fill: none; stroke: black; stroke-width: 2px; .area { fill: lightsteelblue; } } </style> </head> <body> <script> var margin = { top: 40, right: 40, bottom: 40, left: 40 }, width = 500, //interieur height = 300; //interieur var x = d3.scaleTime().range([0, width]), y = d3.scaleLinear().range([height, 0]), c = d3.scaleOrdinal(d3.schemeCategory10); var line = d3.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.price); }); //https://www.d3noob.org/2013/01/filling-area-under-graph.html var area = d3.area() .x(function(d) { return x(d.date) }) .y0(height) // Ordonnées en bas (height car l'origine est en haut à gauche) .y1(function(d) { return y(d.price) }); d3.text('stocks.csv', function(error, raw) { var dsv = d3.dsvFormat(',') var data = dsv.parse(raw); // Nest stock values by symbol. var nested_data = d3.nest() .key(function(d) { return d.symbol; }) .entries(data); // Parse and caculate some values for each nested_data nested_data.forEach(function(s) { s.values.forEach(function(d) { d.date = d3.timeParse("%b %Y")(d.date); d.price = +d.price; }); s.maxPrice = d3.max(s.values, function(d) { return d.price; }); s.sumPrice = d3.sum(s.values, function(d) { return d.price; }); }); // Create the default x-domain. x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(nested_data.map(function(d) { return d.maxPrice; }))]) // Create the container "svg" and 1 subcontainer "g" for margins. 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 + ")"); // From the subcontainer "g", create 4 subsubcontainer "g" for each graph. var g = svg.selectAll("g").data(nested_data).enter() .append("g") // Create a path for the area. g.append("path") .attr("class", "area") .attr("d", function(d) { return area(d.values); }) .style("fill", function(d) { return c(d.key) }) .style("fill-opacity", 0.4) // Add the line path elements. Note: the y-domain is set per element. g.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.values); }) .style("stroke", function(d, i) { return c(d.key) }); // Display last value. g.append("text") .text(function(d, i) { return d.values[0].symbol; }) .attr("y", function(d) { console.log(d.values) return y(d.values[d.values.length - 1].price) }) .attr("x", width + 2) .style("font-family", "monospace"); }); </script> </body>
https://d3js.org/d3.v4.min.js