An example of a surplus/deficit filled line chart. It uses a mask to fill the colour of the area above and below the line.
This is part of a series of visualisations called My Visual Vocabulary which aims to recreate every visualisation in the FT's Visual Vocabulary from scratch using D3.
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0; position:fixed; top:0; right:0; bottom:0; left:0; }
.surplus-deficit-area {
fill: black;
opacity: 0.1;
}
.surplus-deficit-line {
fill: none;
stroke: black;
}
.title {
font-family: sans-serif;
}
</style>
</head>
<body>
<script>
var margin = {top: 100, right: 100, bottom: 100, left: 100};
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 + ")");
var defs = svg.append("defs");
var parseYear = d3.timeParse("%Y");
var x = d3.scaleTime()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y);
function parse(d) {
return {
date: parseYear(d.year),
deficit: +d.deficit_percent
};
}
var area = d3.area()
.x(function(d) { return x(d.date); })
.y1(function(d) { return y(d.deficit); });
var line = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.deficit); });
d3.queue()
.defer(d3.csv, "budget-deficit-gdp.csv", parse)
.await(ready);
function ready(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([Math.floor(d3.min(data, function(d) { return d.deficit; })),
Math.ceil(d3.max(data, function(d) { return d.deficit; }))]);
area.y0(y(0));
defs.append("mask")
.attr("id", "mask1")
.append("path")
.attr("d", function() {
return area(data);
})
.attr("fill", "white")
.attr("opacity", 0.5)
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", y(0))
.attr("fill", "green")
.attr("mask", "url(#mask1)");
svg.append("rect")
.attr("x", 0)
.attr("y", y(0))
.attr("width", width)
.attr("height", y.range()[0] - y(0))
.attr("fill", "red")
.attr("mask", "url(#mask1)");
svg.append("path")
.datum(data)
.attr("class", "surplus-deficit-line")
.attr("d", line)
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("text")
.attr("class", "title")
.attr("transform", "translate(" + width / 2 + ",0)")
.attr("dy", "-2em")
.attr("text-anchor", "middle")
.text("UK government deficit / surplus as percentage of GDP");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
}
</script>
</body>
https://d3js.org/d3.v4.min.js