d3v4
version of horizon pluginWork progressing on Github at d3-horizon. Follow along or even better help out!
Horizon charts combine position and color to reduce vertical space. Start with a standard area chart, then mirror negative values (in blue) or offset them vertically. Click the + button above to increase the number of bands, turning the area into a horizon.
Implemented with the d3.horizon plugin.
xxxxxxxxxx
<html lang="en">
<head>
<meta charset="utf-8">
<title>Horizon Plugin for d3v4</title>
<script src = "//unpkg.com/d3"></script>
<script src = "d3-horizon.js"></script>
<style>
body {
font-family: sans-serif;
}
svg {
position: absolute;
top: 0;
}
#horizon-controls {
position: absolute;
width: 940px;
padding: 10px;
z-index: 1;
}
#horizon-bands {
float: right;
}
</style>
</head>
<body>
<div id="horizon-controls">
<input name="mode" type="radio" value="mirror" id="horizon-mode-mirror" checked><label for="horizon-mode-mirror"> Mirror</label>
<input name="mode" type="radio" value="offset" id="horizon-mode-offset"><label for="horizon-mode-offset"> Offset</label>
<span id="horizon-bands"><span id="horizon-bands-value">1</span> <button class="first">−</button><button class="last">+</button></span>
</div>
<div id="horizon-chart"></div>
<script>
var width = 960,
height = 500;
var chart = d3.horizon()
.width(width)
.height(height)
.bands(1)
.mode("mirror");
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("unemployment.json", function(error, data) {
if (error) throw error;
// Offset so that positive is above-average and negative is below-average.
var mean = data.rate.reduce(function(p, v) { return p + v; }, 0) / data.rate.length;
// Transpose column values to rows.
data = data.rate.map(function(rate, i) {
return [Date.UTC(data.year[i], data.month[i] - 1), rate - mean];
});
// Render the chart.
svg.data([data]).call(chart);
// Enable mode buttons.
d3.selectAll("#horizon-controls input[name=mode]").on("change", function() {
svg.call(chart.mode(this.value));
});
// Enable bands buttons.
d3.selectAll("#horizon-bands button").data([-1, 1]).on("click", function(d) {
var n = Math.max(1, chart.bands() + d);
d3.select("#horizon-bands-value").text(n);
svg.call(chart.bands(n).height(height / n));
});
});
</script>
</body>
</html>