xxxxxxxxxx
<html lang = "en">
<head>
<meta charset="utf-8">
<title> Cancelled Flights in 2016 </title>
<style>
</style></head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 50, right: 50, bottom: 50, left: 50},
width = 1000 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var xScale = d3.scaleBand()
.range([0, width])
.paddingInner(0.05)
.paddingOuter(0.25);
var yScale = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(xScale);
var yAxis = d3.axisLeft()
.scale(yScale);
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 + ")");
var dataset = [];
d3.csv("airlines.csv", function(data) {
data.forEach(function(d) {
// only want values from year 2016, store in new array
// pushing only code and cancellations
if (d.Year == "2016"){
dataset.push({code:d.Code, cancellations:parseInt(d.Cancelled)});
}
});
xScale.domain(dataset.map(function(d) { return d.code; }));
yScale.domain([0, d3.max(dataset, function(d) { return d.cancellations; })]);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.call(yAxis);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d) { return xScale(d.code); })
.attr("y", function(d) { return yScale(d.cancellations); })
.attr("height", function(d) { return height - yScale(d.cancellations); })
.attr("width", xScale.bandwidth())
.attr("fill", "steelblue");
svg.selectAll("text.values")
.data(dataset)
.enter()
.append("text")
.text(function (d) { return d.cancellations; })
.attr("x", function(d) { return xScale(d.code) + xScale.bandwidth()/2; })
.attr("y", function(d) { return yScale(d.cancellations) + 13; })
.style("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
// text label for the y axis
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.attr("font-family", "sans-serif")
.text("Number of Flights Cancelled");
// text label for the x axis
svg.append("text")
.attr("transform",
"translate(" + (width/2) + " ," +
(height + 40) + ")")
.style("text-anchor", "middle")
.attr("font-family", "sans-serif")
.text("Airport Code");
svg.append("text")
.attr("transform", "translate(" + width/2 + "," + -20 + ")")
.style("text-anchor", "middle")
.attr("font-family", "sans-serif")
.text("Number of Flights Cancelled in 2016");
});
</script>
<p><a href="https://github.com/alignedleft/d3-book/blob/master/chapter_09/02_bar_chart_with_scales.html">reference (from book) for adding labels</a></p>
</body>
</html>
https://d3js.org/d3.v4.min.js