D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ShayRomayo
Full window
Github gist
Bar Graph (d3)
<!DOCTYPE html> <meta charset="utf-8"> <style> .bar { fill: steelblue; } </style> <body> <script src="//d3js.org/d3.v4.min.js"></script> <script> // Set graph dimensions and margins var margin = {top: 50, right: 20, bottom: 110, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var targetLabel = "2003/07"; // Set ranges var x = d3.scaleBand() .range([0, width]) .padding(0.1); var y = d3.scaleLinear() .range([height, 0]); // Appends an svg to the body and a group which is moved to the top left margin 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 + ")"); // Get data d3.csv("airlines.csv", function(error, data) { if (error) throw error; var newData = data.filter(function filterCriteria(d) { return d.Label == targetLabel; }) // Format data newData.forEach(function(d) { d.Code = d.Code; d.Delayed = +d.Delayed; }); // Scale the range of the data in the domains x.domain(newData.map(function(d) { return d.Code; })); y.domain([0, d3.max(newData, function(d) { return d.Delayed; })]); // Append rectangles for the bar chart svg.selectAll(".bar") .data(newData) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.Code); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.Delayed); }) .attr("height", function(d) { return height - y(d.Delayed); }); // X Axis svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)) .selectAll("text") .style("text-anchor", "middle") .attr("dx", ".0em") .style("font-size", "12px") .attr("dy", ".75em"); // Y Axis svg.append("g") .call(d3.axisLeft(y)); // Make a title svg.append("text") .attr("x", (width / 2)) .attr("y", 0 - (margin.top / 2)) .attr("text-anchor", "middle") .style("font-size", "20px") .text("Number of Delayed Flights for " + targetLabel); }); </script> </body>
https://d3js.org/d3.v4.min.js