D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ienwhang
Full window
Github gist
AS4 Line Chart D3
<!DOCTYPE html> <html lang="en"> <meta charset="utf-8"> <head> <title>AS4 Line Chart</title> <script src="https://d3js.org/d3.v4.min.js"></script> <style> .line { fill: none; stroke: rgb(70,130,180); stroke-width: 3; opacity: 0.8; } .title { font-family: sans-serif; font-size: 20px; } .axisLabels { font-family: sans-serif; font-size: 14px; } </style> </head> <body> <script type="text/javascript"> // declare dimensions var h = 500, w = 800, margin = 100, axisBuffer = 20; var xAxisYPos = h-margin, yAxisXPos = margin-axisBuffer; // create svg variable var svg = d3.select("body") .append("svg") .attr("height", h) .attr("width", w); // load in data d3.csv("calData.csv", function(dataset) { // make strings numeric dataset.forEach(function(d) { d.PriceIndustrialCoal = +d.PriceIndustrialCoal; d.Year = +d.Year; }); // define scales and axes var xScale = d3.scaleLinear() .domain([d3.min(dataset, function(d) { return d.Year;}), d3.max(dataset, function(d) { return d.Year})]) .range([margin, w-margin]), yScale = d3.scaleLinear() .domain([d3.min(dataset, function(d) { return d.PriceIndustrialCoal;}), Math.ceil((d3.max(dataset, function(d) { return d.PriceIndustrialCoal}))/0.5)*0.5]) .range([h-margin, margin]); var xAxis = d3.axisBottom() .scale(xScale) .tickValues(d3.range(d3.min(dataset, function(d) { return d.Year;}), d3.max(dataset, function(d) { return d.Year;}) + 1, 6)) // add 1 to include upper bound .tickFormat(d3.format("d")), yAxis = d3.axisLeft() .scale(yScale); var line = d3.line() .x(function(d) { return xScale(d.Year); }) .y(function(d) { return yScale(d.PriceIndustrialCoal); }) // draw x axis svg.append("g") .attr("class", "axis") .attr("transform", "translate(0, " + xAxisYPos + ")") .call(xAxis); // draw y axis svg.append("g") .attr("class", "axis") .attr("transform", "translate(" + yAxisXPos + ", 0)") .call(yAxis); // add chart title svg.append("text") .text("Price of Industrial Coal in California by Year") .attr("class", "title") .attr("x", w/2) .attr("y", margin/2) .attr("text-anchor", "middle"); // add axis labels svg.append("text") .attr("class", "axisLabels") .attr("x", w/2) .attr("text-anchor", "middle") .attr("y", h - margin/2) .text("Year"); svg.append("text") .attr("class", "axisLabels") .attr("x", 0) .attr("y", 0) .attr("text-anchor", "middle") .attr("transform", "translate(25, " + h/2 + ")rotate(270)") // translate and rotate y axis label .text("Price ($ per Million BTU)"); // draw line svg.append("path") .datum(dataset) .attr("class", "line") .attr("d", line); }); </script> </body>
https://d3js.org/d3.v4.min.js