Skip to content

Instantly share code, notes, and snippets.

@lorenzopub
Created July 14, 2017 14:54
Show Gist options
  • Save lorenzopub/43b448ffb233aaa0b7e683b72fc8e6e1 to your computer and use it in GitHub Desktop.
Save lorenzopub/43b448ffb233aaa0b7e683b72fc8e6e1 to your computer and use it in GitHub Desktop.
Animated Sort: Small Multiples Single SVG
license: mit
(function() {
d3.grid = function() {
var mode = "equal",
layout = _distributeEqually,
x = d3.scaleOrdinal(),
y = d3.scaleOrdinal(),
size = [1, 1],
actualSize = [0, 0],
nodeSize = false,
bands = false,
padding = [0, 0],
cols, rows;
function grid(nodes) {
return layout(nodes);
}
function _distributeEqually(nodes) {
var i = -1,
n = nodes.length,
_cols = cols ? cols : 0,
_rows = rows ? rows : 0,
col, row;
if (_rows && !_cols) {
_cols = Math.ceil(n / _rows)
} else {
_cols || (_cols = Math.ceil(Math.sqrt(n)));
_rows || (_rows = Math.ceil(n / _cols));
}
if (nodeSize) {
x.domain(d3.range(_cols)).range(d3.range(0, (size[0] + padding[0]) * _cols, size[0] + padding[0]));
y.domain(d3.range(_rows)).range(d3.range(0, (size[1] + padding[1]) * _rows, size[1] + padding[1]));
actualSize[0] = bands ? x(_cols - 1) + size[0] : x(_cols - 1);
actualSize[1] = bands ? y(_rows - 1) + size[1] : y(_rows - 1);
} else if (bands) {
var x = d3.scaleBand()
var y = d3.scaleBand()
x.domain(d3.range(_cols)).range([0, size[0]], padding[0], 0);
y.domain(d3.range(_rows)).range([0, size[1]], padding[1], 0);
actualSize[0] = x.bandwidth()-10;
actualSize[1] = y.bandwidth()-10;
} else {
var x = d3.scalePoint()
var y = d3.scalePoint()
x.domain(d3.range(_cols)).range([0, size[0]]);
y.domain(d3.range(_rows)).range([0, size[1]]);
actualSize[0] = x(1);
actualSize[1] = y(1);
}
while (++i < n) {
col = i % _cols;
row = Math.floor(i / _cols);
nodes[i].x = x(col);
nodes[i].y = y(row);
}
return nodes;
}
grid.size = function(value) {
if (!arguments.length) return nodeSize ? actualSize : size;
actualSize = [0, 0];
nodeSize = (size = value) == null;
return grid;
}
grid.nodeSize = function(value) {
if (!arguments.length) return nodeSize ? size : actualSize;
actualSize = [0, 0];
nodeSize = (size = value) != null;
return grid;
}
grid.rows = function(value) {
if (!arguments.length) return rows;
rows = value;
return grid;
}
grid.cols = function(value) {
if (!arguments.length) return cols;
cols = value;
return grid;
}
grid.bands = function() {
bands = true;
return grid;
}
grid.points = function() {
bands = false;
return grid;
}
grid.padding = function(value) {
if (!arguments.length) return padding;
padding = value;
return grid;
}
return grid;
};
})();
// d3.tip
// Copyright (c) 2013 Justin Palmer
// ES6 / D3 v4 Adaption Copyright (c) 2016 Constantin Gavrilete
// Removal of ES6 for D3 v4 Adaption Copyright (c) 2016 David Gotz
//
// Tooltips for d3.js SVG visualizations
d3.functor = function functor(v) {
return typeof v === "function" ? v : function() {
return v;
};
};
d3.tip = function() {
var direction = d3_tip_direction,
offset = d3_tip_offset,
html = d3_tip_html,
node = initNode(),
svg = null,
point = null,
target = null
function tip(vis) {
svg = getSVGNode(vis)
point = svg.createSVGPoint()
document.body.appendChild(node)
}
// Public - show the tooltip on the screen
//
// Returns a tip
tip.show = function() {
var args = Array.prototype.slice.call(arguments)
if(args[args.length - 1] instanceof SVGElement) target = args.pop()
var content = html.apply(this, args),
poffset = offset.apply(this, args),
dir = direction.apply(this, args),
nodel = getNodeEl(),
i = directions.length,
coords,
scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
nodel.html(content)
.style('position', 'absolute')
.style('opacity', 1)
.style('pointer-events', 'all')
while(i--) nodel.classed(directions[i], false)
coords = direction_callbacks[dir].apply(this)
nodel.classed(dir, true)
.style('top', (coords.top + poffset[0]) + scrollTop + 'px')
.style('left', (coords.left + poffset[1]) + scrollLeft + 'px')
return tip
}
// Public - hide the tooltip
//
// Returns a tip
tip.hide = function() {
var nodel = getNodeEl()
nodel
.style('opacity', 0)
.style('pointer-events', 'none')
return tip
}
// Public: Proxy attr calls to the d3 tip container. Sets or gets attribute value.
//
// n - name of the attribute
// v - value of the attribute
//
// Returns tip or attribute value
tip.attr = function(n, v) {
if (arguments.length < 2 && typeof n === 'string') {
return getNodeEl().attr(n)
} else {
var args = Array.prototype.slice.call(arguments)
d3.selection.prototype.attr.apply(getNodeEl(), args)
}
return tip
}
// Public: Proxy style calls to the d3 tip container. Sets or gets a style value.
//
// n - name of the property
// v - value of the property
//
// Returns tip or style property value
tip.style = function(n, v) {
// debugger;
if (arguments.length < 2 && typeof n === 'string') {
return getNodeEl().style(n)
} else {
var args = Array.prototype.slice.call(arguments);
if (args.length === 1) {
var styles = args[0];
Object.keys(styles).forEach(function(key) {
return d3.selection.prototype.style.apply(getNodeEl(), [key, styles[key]]);
});
}
}
return tip
}
// Public: Set or get the direction of the tooltip
//
// v - One of n(north), s(south), e(east), or w(west), nw(northwest),
// sw(southwest), ne(northeast) or se(southeast)
//
// Returns tip or direction
tip.direction = function(v) {
if (!arguments.length) return direction
direction = v == null ? v : d3.functor(v)
return tip
}
// Public: Sets or gets the offset of the tip
//
// v - Array of [x, y] offset
//
// Returns offset or
tip.offset = function(v) {
if (!arguments.length) return offset
offset = v == null ? v : d3.functor(v)
return tip
}
// Public: sets or gets the html value of the tooltip
//
// v - String value of the tip
//
// Returns html value or tip
tip.html = function(v) {
if (!arguments.length) return html
html = v == null ? v : d3.functor(v)
return tip
}
// Public: destroys the tooltip and removes it from the DOM
//
// Returns a tip
tip.destroy = function() {
if(node) {
getNodeEl().remove();
node = null;
}
return tip;
}
function d3_tip_direction() { return 'n' }
function d3_tip_offset() { return [0, 0] }
function d3_tip_html() { return ' ' }
var direction_callbacks = {
n: direction_n,
s: direction_s,
e: direction_e,
w: direction_w,
nw: direction_nw,
ne: direction_ne,
sw: direction_sw,
se: direction_se
};
var directions = Object.keys(direction_callbacks);
function direction_n() {
var bbox = getScreenBBox()
return {
top: bbox.n.y - node.offsetHeight,
left: bbox.n.x - node.offsetWidth / 2
}
}
function direction_s() {
var bbox = getScreenBBox()
return {
top: bbox.s.y,
left: bbox.s.x - node.offsetWidth / 2
}
}
function direction_e() {
var bbox = getScreenBBox()
return {
top: bbox.e.y - node.offsetHeight / 2,
left: bbox.e.x
}
}
function direction_w() {
var bbox = getScreenBBox()
return {
top: bbox.w.y - node.offsetHeight / 2,
left: bbox.w.x - node.offsetWidth
}
}
function direction_nw() {
var bbox = getScreenBBox()
return {
top: bbox.nw.y - node.offsetHeight,
left: bbox.nw.x - node.offsetWidth
}
}
function direction_ne() {
var bbox = getScreenBBox()
return {
top: bbox.ne.y - node.offsetHeight,
left: bbox.ne.x
}
}
function direction_sw() {
var bbox = getScreenBBox()
return {
top: bbox.sw.y,
left: bbox.sw.x - node.offsetWidth
}
}
function direction_se() {
var bbox = getScreenBBox()
return {
top: bbox.se.y,
left: bbox.e.x
}
}
function initNode() {
var node = d3.select(document.createElement('div'))
node
.style('position', 'absolute')
.style('top', 0)
.style('opacity', 0)
.style('pointer-events', 'none')
.style('box-sizing', 'border-box')
return node.node()
}
function getSVGNode(el) {
el = el.node()
if(el.tagName.toLowerCase() === 'svg')
return el
return el.ownerSVGElement
}
function getNodeEl() {
if(node === null) {
node = initNode();
// re-add node to DOM
document.body.appendChild(node);
};
return d3.select(node);
}
// Private - gets the screen coordinates of a shape
//
// Given a shape on the screen, will return an SVGPoint for the directions
// n(north), s(south), e(east), w(west), ne(northeast), se(southeast), nw(northwest),
// sw(southwest).
//
// +-+-+
// | |
// + +
// | |
// +-+-+
//
// Returns an Object {n, s, e, w, nw, sw, ne, se}
function getScreenBBox() {
var targetel = target || d3.event.target;
while ('undefined' === typeof targetel.getScreenCTM && 'undefined' === targetel.parentNode) {
targetel = targetel.parentNode;
}
var bbox = {},
matrix = targetel.getScreenCTM(),
tbbox = targetel.getBBox(),
width = tbbox.width,
height = tbbox.height,
x = tbbox.x,
y = tbbox.y
point.x = x
point.y = y
bbox.nw = point.matrixTransform(matrix)
point.x += width
bbox.ne = point.matrixTransform(matrix)
point.y += height
bbox.se = point.matrixTransform(matrix)
point.x -= width
bbox.sw = point.matrixTransform(matrix)
point.y -= height / 2
bbox.w = point.matrixTransform(matrix)
point.x += width
bbox.e = point.matrixTransform(matrix)
point.x -= width / 2
point.y -= height / 2
bbox.n = point.matrixTransform(matrix)
point.y += height
bbox.s = point.matrixTransform(matrix)
return bbox
}
return tip
};
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="d3-tip.js"></script>
<script src="d3-grid.js"></script>
<style type="text/css">
body {
font: 11px sans-serif;
margin: 10px;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.bar:hover {
fill: #bcbcbc ;
}
.x.axis path {
display: none;
}
</style>
</head>
<body>
Sort by
<a href="#" class="sort-btn" data-sort="Cons">Conservative</a> /
<a href="#" class="sort-btn" data-sort="Lab">Labour</a>
<!-- / <a href="#" class="sort-btn" data-sort="LD">Lib Dems</a> /
<a href="#" class="sort-btn" data-sort="Gre">Greens</a> /
<a href="#" class="sort-btn" data-sort="PC">Plaid Cymru</a> /
<a href="#" class="sort-btn" data-sort="SNP">SNP</a> /
<a href="#" class="sort-btn" data-sort="UKIP">UKIP</a> -->
<div id="vis"></div>
<script type="text/javascript">
var innerPadding = 30;
var formatPercent = d3.format(".0%");
var dataUrl = "https://raw.githubusercontent.com/ft-interactive/ge2017-dataset/master/financialTimes_ge2017_dataset.csv";
var partyColours = {
"Cons": "#0087dc",
"Gre": "#008066",
"Lab": "#d50000",
"LD": "#FDBB30",
"PC": "#3F8428",
"SNP": "#FFF95D",
"UKIP": "#B3009D"
};
var rectGrid = d3.grid()
.bands()
.size([1000, 1000]);
var x = d3.scaleBand()
.range([0, rectGrid.nodeSize()[0]])
.round(0.1);
// Scales. Note the inverted domain fo y-scale: bigger is up!
var y = d3.scaleLinear()
.range([rectGrid.nodeSize()[1] - innerPadding, 0]);
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-1, 0])
.html(d => Math.round(d.value.percent) + "%" );
var svg = d3.select("body").append("svg")
.attr("width", 1200)
.attr("height", 1200)
.append("g")
.attr("transform", "translate(70, 70)")
.attr("class", "charts");
var nestedGeData = [];
d3.selectAll(".sort-btn")
.on("click", function(d) {
d3.event.preventDefault();
updatedData = sortByParty(nestedGeData, this.dataset.sort);
update(updatedData);
});
d3.csv(dataUrl, function(geData) {
var parties = [
"Cons",
"Gre",
"Lab",
"LD",
"PC",
"SNP",
"UKIP"
]
geData.forEach(function(g) {
var key = g.PCON15CD;
var seat = g.seat;
var values = [];
if (g.con_PC_2017 !== "NA") {
values.push({
"party": "Cons",
"percent": +g.con_PC_2017
});
}
if (g.green_PC_2017 !== "NA") {
values.push({
"party": "Gre",
"percent": +g.green_PC_2017
});
}
if (g.lab_PC_2017 !== "NA") {
values.push({
"party": "Lab",
"percent": +g.lab_PC_2017
});
}
if (g.ld_PC_2017 !== "NA") {
values.push({
"party": "LD",
"percent": +g.ld_PC_2017
});
}
if (g.pc_PC_2017 !== "NA") {
values.push({
"party": "PC",
"percent": +g.pc_PC_2017
});
}
if (g.snp_PC_2017 !== "NA") {
values.push({
"party": "SNP",
"percent": +g.snp_PC_2017
});
}
if (g.ukip_PC_2017 !== "NA") {
values.push({
"party": "UKIP",
"percent": +g.ukip_PC_2017
});
}
nestedGeData.push({
"key": key,
"seat": seat,
"values": values
})
});
x.domain(parties);
slicedData = nestedGeData.slice(0, 100);
update(slicedData);
svg.call(tip);
});
function multipleEnter(constituency) {
var barChart = d3.select(this);
var x = d3.scaleBand();
var sortedValues = constituency.values.sort((a, b) =>
b.percent - a.percent
);
x.domain(sortedValues.map(d => d.party));
x.range([0, rectGrid.nodeSize()[0] - (innerPadding / 2)])
.round(0.1);
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(d => d.slice(0, 2));
y = d3.scaleLinear()
.range([rectGrid.nodeSize()[1] - innerPadding, 0])
.domain([0, 100]);
var yAxis = d3.axisLeft()
.scale(y)
.tickFormat(formatPercent);
barChart
.append("g")
.attr("class", "x axis")
.call(xAxis)
.transition().duration(500)
.delay((d, i) => i * 20)
.attr("transform", function(d) {
return "translate(" + d.x + "," + (d.y + rectGrid.nodeSize()[1] - innerPadding) + ")";
})
barChart.selectAll(".bar")
.data(d => d.values.map(function(a) {
return {
properties: {
key: d.key,
seat: d.seat,
x: d.x,
y: d.y
},
value: a
}
}))
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", d => x(d.value.party))
.attr("width", x.bandwidth())
.attr("y", d => y(d.value.percent))
.attr("height", d => rectGrid.nodeSize()[1] - y(d.value.percent) - innerPadding)
.attr("fill", d => partyColours[d.value.party])
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
.transition().duration(500)
.delay((d, i) => i * 20)
.attr("transform", function(d) {
return "translate(" + d.properties.x + "," + d.properties.y + ")";
})
barChart
.append("text")
.attr("class", "label")
.attr("dy", "-1em")
.attr("text-anchor", "start")
.attr("font-size", "1em")
.text(d => {
if (d.seat.length < 12) {
return d.seat;
} else {
return d.seat.slice(0, 12) + "...";
}
})
.transition().duration(500)
.delay((d, i) => i * 20)
.attr("transform", function(d) {
return "translate(" + d.x + "," + (d.y + (innerPadding / 2)) + ")";
})
}
function multipleUpdate(constituency) {
// some duplication here that should be removed
var barChart = d3.select(this);
var x = d3.scaleBand();
var sortedValues = constituency.values.sort((a, b) =>
b.percent - a.percent
);
x.domain(sortedValues.map(d => d.party));
x.range([0, rectGrid.nodeSize()[0] - (innerPadding / 2)])
.round(0.1);
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(d => d.slice(0, 2));
y = d3.scaleLinear()
.range([rectGrid.nodeSize()[1] - innerPadding, 0])
.domain([0, 100]);
var yAxis = d3.axisLeft()
.scale(y)
.tickFormat(formatPercent);
barChart.select("g.x.axis")
.transition().duration(500)
// .delay((d, i) => i * 20)
.attr("transform", function(d) {
return "translate(" + d.x + "," + (d.y + rectGrid.nodeSize()[1] - innerPadding) + ")";
})
barChart.selectAll(".bar")
.data(d => d.values.map(function(a) {
return {
properties: {
key: d.key,
seat: d.seat,
x: d.x,
y: d.y
},
value: a
}
}))
.transition().duration(500)
.delay((d, i) => i * 20)
.attr("transform", function(d) {
return "translate(" + d.properties.x + "," + d.properties.y + ")";
});
barChart.select("text.label")
.transition().duration(500)
.delay((d, i) => i * 20)
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
function sortByParty(nestedGeData, partyName) {
var sortedDataSet = nestedGeData
.slice(0, 100);
// sortedDataSet = sortedDataSet.filter((a) => {
// for (var i in a.values) {
// if (a.values[i].party === partyName) {
// return true;
// }
// }
// return false;
// });
sortedDataSet = sortedDataSet.sort((a, b) => {
var aPc;
var bPc;
for (var i in a.values) {
if (a.values[i].party === partyName) {
aPc = a.values[i].percent;
}
}
for (var i in b.values) {
if (b.values[i].party === partyName) {
bPc = b.values[i].percent;
}
}
return bPc - aPc;
});
return sortedDataSet;
}
function update(data) {
var update = svg.selectAll("g")
.data(rectGrid(data), d => d.key);
var enter = update.enter()
.append("g")
.attr("class", "chart");
var exit = update.exit();
// follow pattern https://bl.ocks.org/cmgiven/32d4c53f19aea6e528faf10bfe4f3da9
// console.log("Update: " + update.size());
update.each(multipleUpdate);
// console.log("Enter: " + enter.size());
enter.each(multipleEnter);
// console.log("Exit: " + exit.size());
// exit.remove();
update.merge(enter);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment