D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kcsluis
Full window
Github gist
Line Graph, Two Ways
<!DOCTYPE html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> body { font-family: sans-serif; font-size: 10px; } .axis path { display: none; } .axis line { stroke-width:1px; stroke: #ccc; stroke-dasharray: 2px 2px; } .line1 { fill: none; stroke: #bbb; stroke-width: 8px; } .line2 { fill: none; stroke: #000; } </style> </head> <body> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script> <script> var margin = {top: 20, right: 20, bottom: 20, left: 40}; var 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 + ")"); // write a custom parser to address the format your dates are in var parseDate = d3.time.format("%Y-%m").parse; var xScale = d3.time.scale() .range([0,width]); var yScale = d3.scale.linear() .range([height,0]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(yScale) .tickSize(-width) .tickPadding(8) .orient("left"); var line = d3.svg.line() .x(function(d) { return xScale(d.date); }) .y(function(d) { return yScale(d.private_job_change); }); d3.tsv("jobs.tsv", ready); function ready(error, data) { if (error) return console.warn(error); data.forEach(function(d) { d.jobs_change = +d.jobs_change; d.private_job_change = +d.private_job_change; d.unemployment_rate = +d.unemployment_rate; d.date = parseDate(d.month_year); }); xScale.domain(d3.extent(data, function (d) { return d.date; })); yScale.domain(d3.extent(data, function (d) { return d.private_job_change; })); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height) + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis); svg.append("path") .attr("class", "line1") .attr("d", line(data) ); // "d" is the attribute that sets the path // this doesn't preserve data join svg.append("path") .datum(data) .attr("class", "line2") .attr("d", line); // just like data, but you're only doing one thing (datum) // this one does preserve the data join // NEITHER use enter. D3 is weird. }; </script>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js