Skip to content

Instantly share code, notes, and snippets.

@nsonnad
Last active December 10, 2015 19:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nsonnad/4481531 to your computer and use it in GitHub Desktop.
Save nsonnad/4481531 to your computer and use it in GitHub Desktop.
Scatterplot: Social trust vs ease of doing business

A scatterplot using d3js. It maps social trust against ease of doing business in various countries. For tooltips, it makes use of Justin Donaldson's fork of the jQuery plugin tipsy. Data come from the Pew Global Attitudes project and the Doing Business rankings. For a live example see my post on it or http://bl.ocks.org/4481531

<!DOCTYPE html>
<html>
<head>
<title>Trust and Business</title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.tipsy.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="http://onehackoranother.com/projects/jquery/tipsy/stylesheets/tipsy.css" type="text/css" title="no title" charset="utf-8"/>
<style type="text/css">
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
opacity: 1;
}
.axis text { font-size:10px; }
body { font: 12px sans-serif; }
.circles { opacity: .5; }
.tipsy { font-size:11px; margin-top:-10px;}
.guide line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
opacity: 0;
}
</style>
</head>
<body>
<div id="chart">
<script type="text/javascript">
// set the stage
var margin = {t:30, r:20, b:20, l:40 },
w = 600 - margin.l - margin.r,
h = 500 - margin.t - margin.b,
x = d3.scale.linear().range([0, w]),
y = d3.scale.linear().range([h - 60, 0]),
//colors that will reflect geographical regions
color = d3.scale.category10();
var svg = d3.select("#chart").append("svg")
.attr("width", w + margin.l + margin.r)
.attr("height", h + margin.t + margin.b);
// set axes, as well as details on their ticks
var xAxis = d3.svg.axis()
.scale(x)
.ticks(20)
.tickSubdivide(true)
.tickSize(6, 3, 0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.ticks(20)
.tickSubdivide(true)
.tickSize(6, 3, 0)
.orient("left");
// group that will contain all of the plots
var groups = svg.append("g").attr("transform", "translate(" + margin.l + "," + margin.t + ")");
// array of the regions, used for the legend
var regions = ["Asia", "Europe", "Middle East", "N. America", "S. America", "Sub-Saharan Africa"]
// bring in the data, and do everything that is data-driven
d3.csv("trust-business.csv", function(data) {
// sort data alphabetically by region, so that the colors match with legend
data.sort(function(a, b) { return d3.ascending(a.region, b.region); })
console.log(data)
var x0 = Math.max(-d3.min(data, function(d) { return d.trust; }), d3.max(data, function(d) { return d.trust; }));
x.domain([-100, 100]);
y.domain([180, 0])
// style the circles, set their locations based on data
var circles =
groups.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("class", "circles")
.attr({
cx: function(d) { return x(+d.trust); },
cy: function(d) { return y(+d.business); },
r: 8,
id: function(d) { return d.country; }
})
.style("fill", function(d) { return color(d.region); });
// what to do when we mouse over a bubble
var mouseOn = function() {
var circle = d3.select(this);
// transition to increase size/opacity of bubble
circle.transition()
.duration(800).style("opacity", 1)
.attr("r", 16).ease("elastic");
// append lines to bubbles that will be used to show the precise data points.
// translate their location based on margins
svg.append("g")
.attr("class", "guide")
.append("line")
.attr("x1", circle.attr("cx"))
.attr("x2", circle.attr("cx"))
.attr("y1", +circle.attr("cy") + 26)
.attr("y2", h - margin.t - margin.b)
.attr("transform", "translate(40,20)")
.style("stroke", circle.style("fill"))
.transition().delay(200).duration(400).styleTween("opacity",
function() { return d3.interpolate(0, .5); })
svg.append("g")
.attr("class", "guide")
.append("line")
.attr("x1", +circle.attr("cx") - 16)
.attr("x2", 0)
.attr("y1", circle.attr("cy"))
.attr("y2", circle.attr("cy"))
.attr("transform", "translate(40,30)")
.style("stroke", circle.style("fill"))
.transition().delay(200).duration(400).styleTween("opacity",
function() { return d3.interpolate(0, .5); });
// function to move mouseover item to front of SVG stage, in case
// another bubble overlaps it
d3.selection.prototype.moveToFront = function() {
return this.each(function() {
this.parentNode.appendChild(this);
});
};
// skip this functionality for IE9, which doesn't like it
if (!$.browser.msie) {
circle.moveToFront();
}
};
// what happens when we leave a bubble?
var mouseOff = function() {
var circle = d3.select(this);
// go back to original size and opacity
circle.transition()
.duration(800).style("opacity", .5)
.attr("r", 8).ease("elastic");
// fade out guide lines, then remove them
d3.selectAll(".guide").transition().duration(100).styleTween("opacity",
function() { return d3.interpolate(.5, 0); })
.remove()
};
// run the mouseon/out functions
circles.on("mouseover", mouseOn);
circles.on("mouseout", mouseOff);
// tooltips (using jQuery plugin tipsy)
circles.append("title")
.text(function(d) { return d.country; })
$(".circles").tipsy({ gravity: 's', });
// the legend color guide
var legend = svg.selectAll("rect")
.data(regions)
.enter().append("rect")
.attr({
x: function(d, i) { return (40 + i*80); },
y: h,
width: 25,
height: 12
})
.style("fill", function(d) { return color(d); });
// legend labels
svg.selectAll("text")
.data(regions)
.enter().append("text")
.attr({
x: function(d, i) { return (40 + i*80); },
y: h + 24,
})
.text(function(d) { return d; });
// draw axes and axis labels
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + margin.l + "," + (h - 60 + margin.t) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin.l + "," + margin.t + ")")
.call(yAxis);
svg.append("text")
.attr("class", "x label")
.attr("text-anchor", "end")
.attr("x", w + 50)
.attr("y", h - margin.t - 5)
.text("others in society seen as trustworthy*");
svg.append("text")
.attr("class", "y label")
.attr("text-anchor", "end")
.attr("x", -20)
.attr("y", 45)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.text("ease of doing business (rank)");
});
</script>
</div>
</body>
</html>
// tipsy, facebook style tooltips for jquery
// version 1.0.0a
// (c) 2008-2010 jason frame [jason@onehackoranother.com]
// released under the MIT license
(function($) {
function maybeCall(thing, ctx) {
return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
}
// CAUTION the current implementation does not allow for tipsied elements to stay out of DOM (in between events)
// i.e. don't remove, store, then re-insert tipsied elements (and why would you want to do that anyway?)
var garbageCollect = (function() {
var currentInterval;
var to = null;
var tipsies = [];
function _do() {
for (var i = 0; i < tipsies.length;) {
var t = tipsies[i];
// FIXME? the 2nd (non-paranoid) check is from the link below, it should be replaced if a better way is found
// http://stackoverflow.com/questions/4040715/check-if-cached-jquery-object-is-still-in-dom
if (t.options.gcInterval === 0 || t.$element.closest('body').length === 0) {
t.hoverState = 'out';
t.hide();
tipsies.splice(i,1);
} else {
i++;
}
}
}
function _loop() {
to = setTimeout(function() { _do(); _loop(); }, currentInterval);
}
return function(t) {
if (t.options.gcInterval === 0) return;
if (to && t.options.gcInterval < currentInterval) {
clearTimeout(to); to = null;
currentInterval = t.options.gcInterval;
}
tipsies.push(t);
if (!to) _loop();
};
})();
function Tipsy(element, options) {
this.$element = $(element);
this.options = options;
this.enabled = true;
this.fixTitle();
garbageCollect(this);
}
Tipsy.prototype = {
show: function() {
var title = this.getTitle();
if (title && this.enabled) {
var $tip = this.tip();
$tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
$tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
$tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);
var pos = $.extend({}, this.$element.offset(), {
width: this.$element[0].offsetWidth || 0,
height: this.$element[0].offsetHeight || 0
});
if (typeof this.$element[0].nearestViewportElement == 'object') {
// SVG
var el = this.$element[0];
var rect = el.getBoundingClientRect();
pos.width = rect.width;
pos.height = rect.height;
}
var actualWidth = $tip[0].offsetWidth,
actualHeight = $tip[0].offsetHeight,
gravity = maybeCall(this.options.gravity, this.$element[0]);
var tp;
switch (gravity.charAt(0)) {
case 'n':
tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 's':
tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'e':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
break;
case 'w':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
break;
}
if (gravity.length == 2) {
if (gravity.charAt(1) == 'w') {
tp.left = pos.left + pos.width / 2 - 15;
} else {
tp.left = pos.left + pos.width / 2 - actualWidth + 15;
}
}
$tip.css(tp).addClass('tipsy-' + gravity);
$tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
if (this.options.className) {
$tip.addClass(maybeCall(this.options.className, this.$element[0]));
}
if (this.options.fade) {
$tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
} else {
$tip.css({visibility: 'visible', opacity: this.options.opacity});
}
var t = this;
var set_hovered = function(set_hover){
return function(){
t.$tip.stop();
t.tipHovered = set_hover;
if (!set_hover){
if (t.options.delayOut === 0 && t.options.trigger != 'manual') {
t.hide();
} else {
setTimeout(function() {
if (t.hoverState == 'out') t.hide(); }, t.options.delayOut);
}
}
};
};
$tip.hover(set_hovered(true), set_hovered(false));
}
},
hide: function() {
if (this.options.fade) {
this.tip().stop().fadeOut(function() { $(this).remove(); });
} else {
this.tip().remove();
}
},
fixTitle: function() {
var $e = this.$element;
if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
$e.attr('original-title', $e.attr('title') || '').removeAttr('title');
}
if (typeof $e.context.nearestViewportElement == 'object'){
if ($e.children('title').length){
$e.append('<original-title>' + ($e.children('title').text() || '') + '</original-title>')
.children('title').remove();
}
}
},
getTitle: function() {
var title, $e = this.$element, o = this.options;
this.fixTitle();
if (typeof o.title == 'string') {
var title_name = o.title == 'title' ? 'original-title' : o.title;
if ($e.children(title_name).length){
title = $e.children(title_name).html();
} else{
title = $e.attr(title_name);
if (typeof title == 'undefined') title = ''
}
} else if (typeof o.title == 'function') {
title = o.title.call($e[0]);
}
title = ('' + title).replace(/(^\s*|\s*$)/, "");
return title || o.fallback;
},
tip: function() {
if (!this.$tip) {
this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
}
return this.$tip;
},
validate: function() {
if (!this.$element[0].parentNode) {
this.hide();
this.$element = null;
this.options = null;
}
},
enable: function() { this.enabled = true; },
disable: function() { this.enabled = false; },
toggleEnabled: function() { this.enabled = !this.enabled; }
};
$.fn.tipsy = function(options) {
if (options === true) {
return this.data('tipsy');
} else if (typeof options == 'string') {
$(this).each(function(i,el){
if ($(el).data('tipsy')) {
tipsy = $(el).data('tipsy')
tipsy[options]();
}
});
return this;
}
options = $.extend({}, $.fn.tipsy.defaults, options);
if (options.hoverlock && options.delayOut === 0) {
options.delayOut = 100;
}
function get(ele) {
var tipsy = $.data(ele, 'tipsy');
if (!tipsy) {
tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
$.data(ele, 'tipsy', tipsy);
}
return tipsy;
}
function enter() {
var tipsy = get(this);
tipsy.hoverState = 'in';
if (options.delayIn === 0) {
tipsy.show();
} else {
tipsy.fixTitle();
setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
}
}
function leave() {
var tipsy = get(this);
tipsy.hoverState = 'out';
if (options.delayOut === 0) {
tipsy.hide();
} else {
var to = function() {
if (!tipsy.tipHovered || !options.hoverlock){
if (tipsy.hoverState == 'out') tipsy.hide();
}
};
setTimeout(to, options.delayOut);
}
}
if (!options.live) this.each(function() { get(this); });
if (options.trigger != 'manual') {
var binder = options.live ? 'live' : 'bind',
eventIn = options.trigger == 'hover' ? 'mouseenter' : 'focus',
eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
this[binder](eventIn, enter)[binder](eventOut, leave);
}
return this;
};
$.fn.tipsy.defaults = {
className: null,
delayIn: 0,
delayOut: 0,
fade: false,
fallback: '',
gcInterval: 0,
gravity: 'n',
html: false,
live: false,
offset: 0,
opacity: 0.8,
title: 'title',
trigger: 'hover',
hoverlock: false
};
// Overwrite this method to provide options on a per-element basis.
// For example, you could store the gravity in a 'tipsy-gravity' attribute:
// return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
// (remember - do not modify 'options' in place!)
$.fn.tipsy.elementOptions = function(ele, options) {
return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
};
$.fn.tipsy.autoNS = function() {
return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
};
$.fn.tipsy.autoWE = function() {
return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
};
/**
* yields a closure of the supplied parameters, producing a function that takes
* no arguments and is suitable for use as an autogravity function like so:
*
* @param margin (int) - distance from the viewable region edge that an
* element should be before setting its tooltip's gravity to be away
* from that edge.
* @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
* if there are no viewable region edges effecting the tooltip's
* gravity. It will try to vary from this minimally, for example,
* if 'sw' is preferred and an element is near the right viewable
* region edge, but not the top edge, it will set the gravity for
* that element's tooltip to be 'se', preserving the southern
* component.
*/
$.fn.tipsy.autoBounds = function(margin, prefer) {
return function() {
var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
boundTop = $(document).scrollTop() + margin,
boundLeft = $(document).scrollLeft() + margin,
$this = $(this);
if ($this.offset().top < boundTop) dir.ns = 'n';
if ($this.offset().left < boundLeft) dir.ew = 'w';
if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
return dir.ns + (dir.ew ? dir.ew : '');
};
};
})(jQuery);
country trust business gdppc region
Argentina -28 168 17554.119067691 S. America
Bangladesh -15 129 1776.89282453484 Asia
Bolivia -44 155 5099.09217996094 S. America
Brazil -52 130 11639.7194954807 S. America
Britain 30 7 35656.9565075244 Europe
Bulgaria -9 66 14825.0771657591 Europe
Canada 47 17 40369.5851161718 N. America
Chile -56 37 17310.2800735025 S. America
China 78 91 8400.16260969792 Asia
Czech Rep. -18 65 26207.6874532862 Europe
Egypt 21 109 6280.99463624316 Middle East
Ethiopia -5 127 1108.87789464894 Sub-Saharan Africa
France -23 34 35245.6079040649 Europe
Germany 4 20 39491.0260257692 Europe
Ghana -26 64 1871.14094809382 Sub-Saharan Africa
India 7 132 3627.14341118417 Asia
Indonesia 18 128 4636.19678834347 Asia
Israel -31 38 27824.8829745345 Middle East
Italy -26 73 32647.4649463297 Europe
Côte d'Ivoire -14 177 1789.36129264033 Sub-Saharan Africa
Japan -16 24 34313.5804900522 Asia
Jordan 2 106 5966.03602904957 Middle East
Kenya -87 121 1709.50812446534 Sub-Saharan Africa
Kuwait -76 82 54282.5861421787 Middle East
Lebanon -57 115 14608.6694472067 Middle East
Malaysia 13 12 16050.9137705718 Asia
Mali -16 151 1091.11012833182 Sub-Saharan Africa
Mexico -6 48 15266.2097793612 N. America
Morocco -10 97 4952.4368731 Middle East
Nigeria -55 131 2533.05299394733 Sub-Saharan Africa
Pakistan 25 107 2744.83233934761 Asia
Peru -56 43 10233.9466428683 S. America
Poland -7 55 21260.5863057129 Europe
Russia 5 112 21245.9248859672 Europe
South Africa -31 39 10959.7417065231 Sub-Saharan Africa
South Korea -8 8 30286.1443265803 Asia
Senegal -55 166 1967.1329427994 Sub-Saharan Africa
Slovakia -17 46 23910.3901606441 Europe
Spain -23 44 32044.6181153156 Europe
Sweden 82 13 41467.4196021543 Europe
Tanzania -33 134 1512.4885492 Sub-Saharan Africa
Turkey -27 71 17110.1200448083 Europe
Uganda -63 120 1344.9193805938 Sub-Saharan Africa
Ukraine -8 137 7208.0899576188 Europe
United States 12 4 48111.9669095909 N. America
Venezuela -2 180 12748.7408127178 S. America
@bjliu
Copy link

bjliu commented Aug 13, 2014

tooltips go above the top

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment