D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jacquessham
Full window
Github gist
Assignment4 Line Chart
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title> D3: A Line Chart for Hong Kong GDP per Capita</title> <script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script> <style type> .line{ fill: none; stroke:teal; stroke-width: 2px; } </style> </head> <body> <script type="text/javascript"> // Reference: https://bl.ocks.org/d3noob/402dd382a51a4f6eea487f9a35566de0 var title = "Hong Kong GDP per capita Since 1960"; var margin = {top:5, right:5, bottom:100, left:100}; var w_full = 1200; var h_full = 600; var w = w_full - margin.right - margin.left; var h = h_full - margin.top - margin.bottom; var x = d3.scaleTime() .range([0,w]); var y = d3.scaleLinear() .range([h,0]); var parseTime = d3.timeParse("%Y"); var valueLine = d3.line() .x(function(d){return x(d.Year); }) .y(function(d){return y(d.GDPperCapita); }); var svg = d3.select("body") .append("svg") .attr("width",w_full) .attr("height",50) .append("g") .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); svg.append("text") .text(title) .attr("x",w_full/2) .attr("y",25) .style("text-anchor","middle") .style("fill","black") .style("font-size",16); // Set up a svg on the top to put title d3.csv("hkgdppercapita.csv", function(error, data){ if(error) throw error; data.forEach(function(d){ d.Year = parseTime(d.Year.toString()); d.GDPperCapita = +d.GDPperCapita; }); x.domain(d3.extent(data,function(d){return d.Year;})); y.domain([0,d3.max(data,function(d){return 1.2*d.GDPperCapita;})]); svg = d3.select('body').append('svg') .attr("width",w_full) .attr("height",h_full) .append("g") .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); var xAxis = d3.axisBottom(x); var yAxis = d3.axisLeft(y); var xAxisEle = svg.append('g') .classed('x axis',true) .attr('transform','translate(0,'+h+')') .call(xAxis); // Append x-axis and its labels xAxisEle.append("text") .attr("x",w_full/2) .attr("y",100) .style("text-anchor","middle") .style("fill","black") .attr("dy","-4.5em") .style("font-size",12) .text("Year"); var yAxisEle = svg.append("g") .classed("y axis",true) .call(yAxis); var yText = yAxisEle.append("text") .attr('transform', 'rotate(-90)translate(-' + h/2 + ',0)') .style("text-anchor","middle") .style("fill","black") .attr("dy","-4.5em") .style("font-size",12) .text("GDP per Capita (US$)"); // Append y-axis and its labels svg.append("path") .data([data]) .attr("class","line") .attr("d",valueLine); // Plot the Line }) </script> </body> </html>
https://d3js.org/d3.v4.min.js