Skip to content

Instantly share code, notes, and snippets.

@Kcnarf
Last active August 8, 2019 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcnarf/7ebd3a8baebb3a7e03f3e4e147a2bc02 to your computer and use it in GitHub Desktop.
Save Kcnarf/7ebd3a8baebb3a7e03f3e4e147a2bc02 to your computer and use it in GitHub Desktop.
#SWDChallenge - Sept '18
height: 500

This chart is my contribution to the september 2018 #SWDChallenge.

I wanted the chart to focus on rank shifts so I designed it this way:

  • colours focus attention on rank shifts; any other information (such as precentages) gives the reader a deeper understanding, but uses less eye-catching colours (i.e. greys) in order to not disturb the main message
  • two distinct colours differentiate rise and fall, respectively lime-green and pink-red (more on this colour-blindness friendly palette below)
  • the chart is vertically oriented, so that shapes of the chords themselves indicate a rise or a fall

Also, even if my first idea was to use a flow chart, it was more appealing and fun to use a circular flow chart :-) Many thanks to Nadieh Bremer for sharing How to create a Flow Diagram with a Circular Twist.

Finally, regarding the color palette, I first use a basic green/red, but @storywithdata immediatly noticed that it was not color-blindness friendly. I first didn't know how to modify the palette. @visualizingdata brought me the response I was looking for in its wonderfull blog five ways to design for red-green colour-blindness (I choose option #2).

Acknowledgments to :

customChordLayout = function() {
var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
function relayout() {
var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
chords = [];
groups = [];
k = 0, i = -1;
while (++i < n) {
x = 0, j = -1;
while (++j < n) {
x += matrix[i][j];
}
groupSums.push(x);
subgroupIndex.push(d3.range(n).reverse());
k += x;
}
if (sortGroups) {
groupIndex.sort(function(a, b) {
return sortGroups(groupSums[a], groupSums[b]);
});
}
if (sortSubgroups) {
subgroupIndex.forEach(function(d, i) {
d.sort(function(a, b) {
return sortSubgroups(matrix[i][a], matrix[i][b]);
});
});
}
k = (τ - padding * n) / k;
x = 0, i = -1;
while (++i < n) {
x0 = x, j = -1;
while (++j < n) {
var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
subgroups[di + "-" + dj] = {
index: di,
subindex: dj,
startAngle: a0,
endAngle: a1,
value: v
};
}
groups[di] = {
index: di,
startAngle: x0,
endAngle: x,
value: (x - x0) / k
};
x += padding;
}
i = -1;
while (++i < n) {
j = i - 1;
while (++j < n) {
var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
if (source.value || target.value) {
chords.push(source.value < target.value ? {
source: target,
target: source
} : {
source: source,
target: target
});
}
}
}
if (sortChords) resort();
}
function resort() {
chords.sort(function(a, b) {
return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
});
}
chord.matrix = function(x) {
if (!arguments.length) return matrix;
n = (matrix = x) && matrix.length;
chords = groups = null;
return chord;
};
chord.padding = function(x) {
if (!arguments.length) return padding;
padding = x;
chords = groups = null;
return chord;
};
chord.sortGroups = function(x) {
if (!arguments.length) return sortGroups;
sortGroups = x;
chords = groups = null;
return chord;
};
chord.sortSubgroups = function(x) {
if (!arguments.length) return sortSubgroups;
sortSubgroups = x;
chords = null;
return chord;
};
chord.sortChords = function(x) {
if (!arguments.length) return sortChords;
sortChords = x;
if (chords) resort();
return chord;
};
chord.chords = function() {
if (!chords) relayout();
return chords;
};
chord.groups = function() {
if (!groups) relayout();
return groups;
};
return chord;
};
////////////////////////////////////////////////////////////
/////////////// Custom Chord Function //////////////////////
//////// Pulls the chords pullOutSize pixels apart /////////
////////////////// along the x axis ////////////////////////
////////////////////////////////////////////////////////////
///////////// Created by Nadieh Bremer /////////////////////
//////////////// VisualCinnamon.com ////////////////////////
////////////////////////////////////////////////////////////
//// Adjusted from the original d3.svg.chord() function ////
///////////////// from the d3.js library ///////////////////
//////////////// Created by Mike Bostock ///////////////////
////////////////////////////////////////////////////////////
stretchedChord = function() {
var source = d3_source,
target = d3_target,
radius = d3_svg_chordRadius,
startAngle = d3_svg_arcStartAngle,
endAngle = d3_svg_arcEndAngle,
pullOutSize = 0;
var π = Math.PI,
halfπ = π / 2;
function subgroup(self, f, d, i) {
var subgroup = f.call(self, d, i),
r = radius.call(self, subgroup, i),
a0 = startAngle.call(self, subgroup, i) - halfπ,
a1 = endAngle.call(self, subgroup, i) - halfπ;
return {
r: r,
a0: [a0],
a1: [a1],
p0: [ r * Math.cos(a0), r * Math.sin(a0)],
p1: [ r * Math.cos(a1), r * Math.sin(a1)]
};
}
function arc(r, p, a) {
var sign = (p[0] >= 0 ? 1 : -1);
return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + (p[0] + sign*pullOutSize) + "," + p[1];
}
function curve(p1) {
var sign = (p1[0] >= 0 ? 1 : -1);
return "Q 0,0 " + (p1[0] + sign*pullOutSize) + "," + p1[1];
}
/*
M = moveto
M x,y
Q = quadratic Bézier curve
Q control-point-x,control-point-y end-point-x, end-point-y
A = elliptical Arc
A rx, ry x-axis-rotation large-arc-flag, sweep-flag end-point-x, end-point-y
Z = closepath
M251.5579641956022,87.98204731514328
A266.5,266.5 0 0,1 244.49937503334525,106.02973926358392
Q 0,0 -177.8355222451483,198.48621369706098
A266.5,266.5 0 0,1 -191.78901944612068,185.0384338992728
Q 0,0 251.5579641956022,87.98204731514328
Z
*/
function chord(d, i) {
var s = subgroup(this, source, d, i),
t = subgroup(this, target, d, i),
sign = (s.p0[0] >= 0 ? 1 : -1);
return "M" + (s.p0[0] + sign*pullOutSize) + "," + s.p0[1] +
arc(s.r, s.p1, s.a1 - s.a0) +
curve(t.p0) +
arc(t.r, t.p1, t.a1 - t.a0) +
curve(s.p0) +
"Z";
}//chord
chord.radius = function(v) {
if (!arguments.length) return radius;
radius = d3_functor(v);
return chord;
};
chord.pullOutSize = function(v) {
if (!arguments.length) return pullOutSize;
pullOutSize = v;
return chord;
};
chord.source = function(v) {
if (!arguments.length) return source;
source = d3_functor(v);
return chord;
};
chord.target = function(v) {
if (!arguments.length) return target;
target = d3_functor(v);
return chord;
};
chord.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return chord;
};
chord.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return chord;
};
function d3_svg_chordRadius(d) {
return d.radius;
}
function d3_source(d) {
return d.source;
}
function d3_target(d) {
return d.target;
}
function d3_svg_arcStartAngle(d) {
return d.startAngle;
}
function d3_svg_arcEndAngle(d) {
return d.endAngle;
}
function d3_functor(v) {
return typeof v === "function" ? v : function() {
return v;
};
}
return chord;
}//stretchedChord
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Rise and Fall of Tourist Destination - #SWDChallenge sept '18</title>
<!-- load entire D3.js -->
<!--script src="http://d3js.org/d3.v5.js"></script-->
<!-- or load only required packages -->
<script src="https://d3js.org/d3-selection.v1.min.js"></script>
<script src="https://d3js.org/d3-color.v1.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-path.v1.min.js"></script>
<script src="https://d3js.org/d3-shape.v1.min.js"></script>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-ease.v1.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src="https://d3js.org/d3-timer.v1.min.js"></script>
<script src="https://d3js.org/d3-transition.v1.min.js"></script>
<script src="d3.stretched.chord.js"></script>
<script src="d3.layout.chord.sort.js"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Open Sans & CSS -->
<link href='https://fonts.googleapis.com/css?family=Open+Sans:700,400,300' rel='stylesheet' type='text/css'>
<style>
body {
font-family: 'Open Sans', sans-serif;
font-size: 12px;
font-weight: 400;
color: #525252;
text-align: center;
background-color: #fafafa;
}
#chart {
position: absolute;
top: 0px;
}
#title {
font-size: 20px;
padding: 10px;
}
#subtitle {
font-size: 16px;
}
#years {
font-size: 16px;
padding-top: 35px;
color: grey;
}
#year-2000 {
padding-right : 65px;
}
#year-2016 {
padding-left : 65px;
}
#legend {
position: absolute;
bottom: 60px;
width: 20%;
padding-left: 40%;
color: lightgrey;
}
.footer {
position: absolute;
bottom: 10px;
color: lightgrey;
}
.footer.left {
left: 10px;
}
.footer.center {
width: 960px;
margin-left: auto;
margin-right: auto;
}
.footer.right {
right:10px;
}
.footer a {
color: lightgrey;
text-decoration: none;
}
.rise {
color: #9BBF85;
}
.fall {
color: #B3589A;
}
line {
stroke: #000;
stroke-width: 1.px;
}
text {
font-size: 8px;
}
.titles{
font-size: 12px;
fill: grey;
}
path.chord {
fill-opacity: .80;
}
</style>
</head>
<body>
<div id="title">THE <span class="rise">RISE</span> AND <span class="fall">FALL</span> OF TOURIST DESTINATIONS</div>
<div id="subtitle"> From 2000 to 2016 <span class="rise">Asia Pacific</span> became the prefered tourist destination at the expense of <span class="fall">Europe</span> and <span class="fall">North America</span>.</div>
<div id="years">
<span id="year-2000">2000</span>
<span id="inter-year"></span>
<span id="year-2016">2016</span>
</div>
<div id="legend">
semi-circles show regional share of total tourism contribution to global GDP.
</div>
<div id="chart"></div>
<div class="footer center"><a href="https://bl.ocks.org/Kcnarf/7ebd3a8baebb3a7e03f3e4e147a2bc02">https://bl.ocks.org/Kcnarf/7ebd3a8baebb3a7e03f3e4e147a2bc02</a></div>
<div class="footer left"><a href="http://www.storytellingwithdata.com/blog/2018/8/24/swdchallenge-how-would-you-makeover-this-graph">#SWDChallenge - Sept'18</a></div>
<div class="footer right"><a href="https://twitter.com/_Kcnarf">Designed by: @_kcnarf</a></div>
<script src="script.js"></script>
</body>
</html>
////////////////////////////////////////////////////////////
//////////////////////// Set-up ////////////////////////////
////////////////////////////////////////////////////////////
var screenWidth = $(window).width(),
mobileScreen = (screenWidth > 400 ? false : true);
var margin = {left: 0, top: 20, right: 0, bottom: 0},
svgWidth = 960,
svgHeight = 500
width = svgWidth - margin.left - margin.right,
height = svgHeight - margin.top - margin.bottom;
var svg = d3.select("#chart").append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
var wrapper = svg.append("g").attr("class", "chordWrapper")
.attr("transform", "translate(" + (width / 2 + margin.left) + "," + (height / 2 + margin.top) + ")");;
var outerRadius = Math.min(width, height) / 3,
innerRadius = outerRadius * 0.95,
pullOutSize = 50,
opacityDefault = 1, //default opacity of chords
opacityLow = 0.2; //hover opacity of those chords not hovered over
////////////////////////////////////////////////////////////
////////////////////////// Data ////////////////////////////
////////////////////////////////////////////////////////////
var Names = ["Asia Pacific - 31%","Europe - 27%","North America - 25%","Latin America - 4%","Middle East - 3%","Other - 10%","","Other - 10%","Middle East - 3%","Latin America - 4%","Asia Pacific - 21%","North America - 27%","Europe - 35%",""];
var respondents = 100,
emptyPerc = 0.4, //What % of the circle should become empty
emptyStroke = Math.round(respondents*emptyPerc),
es = emptyStroke,
areaToIndex = {};
Names.forEach(function(d, i) {
areaToIndex[d] = i;
})
matrix = [];
var matrix = [
[00,00,00,00,00,00,00,00,00,00,31,00,00,00], //Asia Pacific '16
[00,00,00,00,00,00,00,00,00,00,00,00,27,00], //Europe '16
[00,00,00,00,00,00,00,00,00,00,00,25,00,00], //North America '16
[00,00,00,00,00,00,00,00,00,04,00,00,00,00], //Latin America '16
[00,00,00,00,00,00,00,00,03,00,00,00,00,00], //Meadle East '16
[00,00,00,00,00,00,00,10,00,00,00,00,00,00], //Other '16
[00,00,00,00,00,00,00,00,00,00,00,00,00,es], //Dummy stroke
[00,00,00,00,00,10,00,00,00,00,00,00,00,00], //Other 2k
[00,00,00,00,03,00,00,00,00,00,00,00,00,00], //Middle East 2k
[00,00,00,04,00,00,00,00,00,00,00,00,00,00], //Latin America 2k
[21,00,00,00,00,00,00,00,00,00,00,00,00,00], //Asia Pacific 2k
[00,00,27,00,00,00,00,00,00,00,00,00,00,00], //North America 2k
[00,35,00,00,00,00,00,00,00,00,00,00,00,00], //Europe 2k
[00,00,00,00,00,00,es,00,00,00,00,00,00,00] //Dummy stroke
];
//Calculate how far the Chord Diagram needs to be rotated clockwise to make the dummy
//invisible chord center vertically
var offset = (2 * Math.PI) * (emptyStroke/(respondents + emptyStroke))/4;
//Custom sort function of the chords to keep them in the original order
function customSort(a,b) {
return 1;
};
//Custom sort function of the chords to keep them in the original order
var chord = customChordLayout() //d3.layout.chord()//Custom sort function of the chords to keep them in the original order
.padding(.02)
.sortChords(d3.descending) //which chord should be shown on top when chords cross. Now the biggest chord is at the bottom
.matrix(matrix);
var arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.startAngle(startAngle) //startAngle and endAngle now include the offset in degrees
.endAngle(endAngle);
var path = stretchedChord()
.radius(innerRadius)
.startAngle(startAngle)
.endAngle(endAngle)
.pullOutSize(pullOutSize);
////////////////////////////////////////////////////////////
//////////////////// Draw outer Arcs ///////////////////////
////////////////////////////////////////////////////////////
var g = wrapper.selectAll("g.group")
.data(chord.groups)
.enter().append("g")
.attr("class", "group")
.on("mouseover", fade(opacityLow))
.on("mouseout", fade(opacityDefault));
g.append("path")
.style("fill", function(d,i) { return (Names[i] === "" ? "none" : "lightgrey"); })
.style("pointer-events", function(d,i) { return (Names[i] === "" ? "none" : "auto"); })
.attr("d", arc)
.attr("transform", function(d, i) { //Pull the two slices apart
d.pullOutSize = pullOutSize * ( d.startAngle + 0.001 > Math.PI ? -1 : 1);
return "translate(" + d.pullOutSize + ',' + 0 + ")";
});
////////////////////////////////////////////////////////////
////////////////////// Append Names ////////////////////////
////////////////////////////////////////////////////////////
//The text also needs to be displaced in the horizontal directions
//And also rotated with the offset in the clockwise direction
g.append("text")
.each(function(d) { d.angle = ((d.startAngle + d.endAngle) / 2) + offset;})
.attr("dy", ".35em")
.attr("class", "titles")
.attr("text-anchor", function(d) { return d.angle > Math.PI ? "end" : "start"; })
.attr("transform", function(d,i) {
var c = arc.centroid(d);
var sign = Math.sign(d.pullOutSize);
var dy = 0;
if (Names[d.index].indexOf("Latin America") != -1) { dy = 4; }
if (Names[d.index].indexOf("Middle East") != -1) { dy = 9; }
if (Names[d.index].indexOf("Other") != -1) { dy = 10; }
return "translate(" + (c[0] + d.pullOutSize) + "," + c[1] + ")"
+ "translate(" + [sign*15, dy] + ")"
})
.text(function(d,i) { return Names[i]; });
////////////////////////////////////////////////////////////
//////////////////// Draw inner chords /////////////////////
////////////////////////////////////////////////////////////
var chords = wrapper.selectAll("path.chord")
.data(chord.chords().sort(function(c0,c1){
return c1.source.index - c0.source.index;
}))
.enter().append("path")
.attr("class", "chord")
.style("stroke", "none")
.style("fill", function(d) {
var name = Names[d.source.index];
if (name.indexOf("Asia") !== -1) {
return "#9BBF85";
} else if (name.indexOf("Europe") !== -1) {
return "#B3589A";
} else if (name.indexOf("North America") !== -1) {
return "#B3589A";
}
else {
return "lightgrey";
}
})
.style("opacity", function(d) { return (Names[d.source.index] === "" ? 0 : opacityDefault); }) //Make the dummy strokes have a zero opacity (invisible)
.style("pointer-events", function(d,i) { return (Names[d.source.index] === "" ? "none" : "auto"); }) //Remove pointer events from dummy strokes
.attr("d", path);
////////////////////////////////////////////////////////////
///////////////////////// Tooltip //////////////////////////
////////////////////////////////////////////////////////////
/*
//Arcs
g.append("title")
.text(function(d, i) {return Math.round(d.value) + " people in " + Names[i];});
//Chords
chords.append("title")
.text(function(d) {
return ""+ Names[d.target.index] + ": from " + Math.round(d.source.value)+ "% to " + Math.round(d.target.value) + "%";
});
*/
////////////////////////////////////////////////////////////
////////////////// Extra Functions /////////////////////////
////////////////////////////////////////////////////////////
//Include the offset in de start and end angle to rotate the Chord diagram clockwise
function startAngle(d) { return d.startAngle + offset; }
function endAngle(d) { return d.endAngle + offset; }
// Returns an event handler for fading a given chord group
function fade(opacity) {
return function(d, i) {
svg.selectAll("path.chord")
.filter(function(d) { return d.source.index !== i && d.target.index !== i && Names[d.source.index] !== ""; })
.transition("fadeOnArc")
.style("opacity", opacity);
};
}//fade
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment