D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ShayRomayo
Full window
Github gist
Trellis Plot (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 targetYear = "2004"; var targetLabel1 = "ATL"; var targetLabel2 = "BOS"; var targetLabel3 = "LAX"; // Set ranges var x = d3.scaleBand() .range([0, width / 12]) .padding(0.1); var x2 = d3.scaleBand() .range([0, width]) .padding(0.1); var y = d3.scaleLinear() .range([height - 20, 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.Code == targetLabel1) || (d.Code == targetLabel2) || (d.Code == targetLabel3)) && (d.Year == targetYear); }) // Format data newData.forEach(function(d) { d.Code = d.Code; d.Delayed = +d.Delayed; d.Month = +d.Month; d.MonthName = d.MonthName; }); // Scale the range of the data in the domains x.domain(newData.map(function(d) { return d.Code; })); x2.domain(newData.map(function(d) { return d.MonthName; })) 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) + ((width / 12) * (d.Month - 1)); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.Delayed); }) .attr("height", function(d) { return height - y(d.Delayed) - 20; }); // X Axis var i; for (i = 0 ; i < 12 ; i ++) { svg.append("g") .attr("transform", "translate(" + ((width / 12) * i) + "," + (height - 20) + ")") .call(d3.axisBottom(x)) .selectAll("text") .style("text-anchor", "middle") .attr("dx", ".0em") .style("font-size", "12px") .attr("dy", ".75em"); } svg.append("g") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x2)) .selectAll("text") .style("text-anchor", "middle") .attr("dx", ".0em") .style("font-size", "14px") .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 in " + targetYear); }); </script> </body>
https://d3js.org/d3.v4.min.js