D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
EmbraceLife
Full window
Github gist
step3
Built with
blockbuilder.org
<!DOCTYPE html> <meta charset="utf-8"> <style> .axis--x path { display: none; } .line { fill: none; stroke: steelblue; stroke-width: 1.5px; } </style> <svg width="960" height="500"></svg> <script src="//d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), margin = {top: 20, right: 80, bottom: 30, left: 50}, width = svg.attr("width") - margin.left - margin.right, height = svg.attr("height") - margin.top - margin.bottom, g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var parseTime = d3.timeParse("%Y%m%d"); var x = d3.scaleTime().range([0, width]), y = d3.scaleLinear().range([height, 0]), z = d3.scaleOrdinal(d3.schemeCategory10); var line = d3.line() .curve(d3.curveBasis) .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.temperature); }); // 1. tranform each row of data as needed // 1.1 d => a row of data turn => as object // 1.2 columns => column names // 1.3 _ is index of each row, ignored here function type(d, _, columns) { // 2. apply data to date format func d.date = parseTime(d.date); // 3 convert temperature from string type to numeric type // 3.1 loop every column except the date column // 3.2 assign each column name to variable c // 3.3 extract each city's temperature value of a row using column name // 3.4 + convert string number to numeric number for (var i = 1, n = columns.length, c; i < n; ++i) d[c = columns[i]] = +d[c]; return d; } // 4. load data file and preprocess data // 4.1 d3.tsv("data.tsv").row(type).get(function(error, data){ }) d3.tsv("data.tsv", type, function(error, data) { // 4.2 the transformed data is stored inside variable data // 4.3 data is array of objects, each row is an object // 4.4 each object has 4 named values: date and 3 cities' temp console.log(data); // ignore it for now if (error) throw error; // 5. if var data organises dataset by rows, var cities organises dataset by columns // 5.1 create an array with 3 city names var cities = data.columns.slice(1) // 5.2 loop each city name .map(function(id) { // 5.3 for each city name return an object: 2 named values return { // 5.4 id: city name id: id, // 5.5 values: array of objects created using every row of data values: data.map(function(d) { // 5.6 inside each object: 2 named values: return {date: d.date, temperature: d[id]}; }) }; }); // test it console.log(cities); }); </script>
https://d3js.org/d3.v4.min.js