D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
lmelgar
Full window
Github gist
Week 6: Labeled Lines.
<!DOCTYPE html> <!-- Modification of an example by Scott Murray from Knight D3 course --> <html lang="en"> <head> <meta charset="utf-8"> <title>Line Chart with Multiple Lines</title> <style type="text/css"> body { background-color: white; font-family: Helvetica, Arial, sans-serif; } h1 { font-size: 24px; margin: 0; } p { font-size: 14px; margin: 10px 0 0 0; } svg { background-color: white; } path.line { fill: none; stroke: orange; stroke-width: 2px; } .axis path, .axis line { fill: none; stroke: black; stroke-width: 1px; } .axis text { font-family: sans-serif; font-size: 11px; } </style> </head> <body> <h1>CO2 Emissions by Country</h1> <p>Carbon dioxide emissions, 1961-2010. Data not available for the entire period for all countries. Source: <a href="https://data.worldbank.org/indicator/EN.ATM.CO2E.KT?page=6">World Bank</a>, 2014</p> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> <script type="text/javascript"> //Dimensions and padding var width = 700; var height = 600; var margin = {top: 20, right: 10, bottom: 40, left:100}; //Set up date formatting and years var dateFormat = d3.time.format("%Y"); //Set up scales var xScale = d3.time.scale() .range([ margin.left, width - margin.right - margin.left ]); var yScale = d3.scale.linear() .range([ margin.top, height - margin.bottom ]); //Configure axis generators var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(15) .tickFormat(function(d) { return dateFormat(d); }) .outerTickSize([0]); var yAxis = d3.svg.axis() .scale(yScale) .orient("left") .outerTickSize([0]); //Configure line generator // each line dataset must have a d.year and a d.amount for this to work. var line = d3.svg.line() .x(function(d) { return xScale(dateFormat.parse(d.year)); }) .y(function(d) { return yScale(+d.amount); }); //Create the empty SVG image var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height); //Load data d3.csv("co2_emissions.csv", function(data) { //Data is loaded in, but we need to restructure it. //Remember, each line requires an array of x/y pairs; //that is, an array of arrays, like so: // // [ [x: 1, y: 1], [x: 2, y: 2], [x: 3, y: 3] ] // //We, however, are using 'year' as x and 'amount' as y. //We also need to know which country belongs to each //line, so we will build an array of objects that is //structured like this: /* [ { country: "Australia", emissions: [ { year: 1961, amount: 90589.568 }, { year: 1962, amount: 94912.961 }, { year: 1963, amount: 101029.517 }, … ] }, { country: "Bermuda", emissions: [ { year: 1961, amount: 176.016 }, { year: 1962, amount: 157.681 }, { year: 1963, amount: 150.347 }, … ] }, … ] */ //Note that this is an array of objects. Each object //contains two values, 'country' and 'emissions'. //The 'emissions' value is itself an array, containing //more objects, each one holding 'year' and 'amount' values. //New array with all the years, for referencing later var years = ["1961", "1962", "1963", "1964", "1965", "1966", "1967", "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"]; // or you could get this by doing: // var years = d3.keys(data[0]).slice(0, 54-4); // //Create a new, empty array to hold our restructured dataset var dataset = []; //Loop once for each row in data data.forEach(function (d, i) { var myEmissions = []; //Loop through all the years - and get the emissions for this data element years.forEach(function (y) { // If value is not empty if (d[y]) { //Add a new object to the new emissions data array - for year, amount myEmissions.push({ year: y, amount: d[y] // this is the value for, for example, d["2004"] }); } }); //Create new object with this country's name and empty array // d is the current data row... from data.forEach above. dataset.push( { country: d.countryName, emissions: myEmissions // we just built this! } ); }); //Uncomment to log the original data to the console // console.log(data); //Uncomment to log the newly restructured dataset to the console console.log(dataset); //Set scale domains - max and mine of the years xScale.domain( d3.extent(years, function(d) { return dateFormat.parse(d); })); // max of emissions to 0 (reversed, remember) yScale.domain([ d3.max(dataset, function(d) { return d3.max(d.emissions, function(d) { return +d.amount; }); }), 0 ]); //Make a group for each country var groups = svg.selectAll("g") .data(dataset) .enter() .append("g"); //Append a title with the country name (so we get easy tooltips) groups.append("title") .text(function(d) { return d.country; }); //Within each group, create a new line/path, //binding just the emissions data to each one groups.selectAll("path") .data(function(d) { // because there's a group with data already... return [ d.emissions ]; // it has to be an array for the line function }) .enter() .append("path") .attr("class", "line") .attr("d", line); /*groups.append('text.labels') .datum(function(d) { if (dataset[0] === "China" || dataset[0] === "United States") { var j = d.emissions.length - 1; while(d.emissions[j].position == 0 && j > 0) { j--; } return {country: d.country, emissions: d.amount[j]}; } }) .attr("transform", function(d) { return "translate(" + xScale(dataset[1].year) + "," + yScale(dataset[1].amount) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .text(function(d) { return dataset[0]; });*/ //Axes svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height - margin.bottom) + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + margin.left + ",0)") .call(yAxis); svg.append("text") .attr("transform", "translate(" + (width - margin.left) + "," + yScale(dataset[40].emissions[49].amount) + ")") .attr("dy", ".35em") .attr("text-anchor", "start") .attr("font-size", "14") .attr("font-weight", "bold") .style("fill", "rgba(155,155,155,1)") .text("China"); svg.append("text") .attr("transform", "translate(" + (width - margin.left) + "," + yScale(dataset[207].emissions[49].amount) + ")") .attr("dy", ".35em") .attr("text-anchor", "start") .attr("font-size", "14") .attr("font-weight", "bold") .style("fill", "rgba(155,155,155,1)") .text("United States"); }); // end of data csv </script> </body> </html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js