D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kmix27
Full window
Github gist
simple_nations_linegraph
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> var margin = {top: 20, right: 50, bottom: 40, left: 50}, width = 960 - margin.left - margin.right, height = 500 - 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 g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var parseTime = d3.timeParse("%y"); var line = d3.line() .x(function(d){return x(d[0])}) .y(function(d){return y(d[1])}) // .curve() function filterJSON(json, location, value){ var result = []; json.forEach( function(val, idx, arr){ if(val.name == location){ result.push(val[value])} }) return result[0]; } var x = d3.scaleLinear() .range([margin.left,width]) var y = d3.scaleTime() .range([height,margin.bottom]) d3.json("nations.json", function(error,json){ if (error) throw error; // this builds one line for angola income data = filterJSON(json, "Angola", "income") //sets data domain for x and y x.domain(d3.extent(data, function(d){return d[0]})) y.domain(d3.extent(data, function(d){return d[1]})) //appends x axis g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) // appends y axis g.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y)) .append("text") .attr("fill", "#000") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", "0.71em") .attr("text-anchor", "end") .text("income ($)"); // appends line g.append("path") .datum(data) .attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-linejoin", "round") .attr("stroke-linecap", "round") .attr("stroke-width", 1.5) .attr("d", line); // end angola income }); </script> </body>
https://d3js.org/d3.v4.min.js