Skip to content

Instantly share code, notes, and snippets.

@devrand
Last active August 28, 2016 17:44
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 devrand/d55031258473820f3440 to your computer and use it in GitHub Desktop.
Save devrand/d55031258473820f3440 to your computer and use it in GitHub Desktop.
Elections-2014, Ukraine. Choropleth with jenks + force-directed labels + connected monobar chart
name id Poroshenko Tymoshenko Lyashko Grytzenko Tigipko Dobkin Rabinovych Bogomolez Symonenko Tyagnybok Yarosh Others
Vinnytsya region 3159 67.32 15.57 5.55 4.11 1.68 0.47 0.85 0.94 0.64 0.84 0.37 1.66
Volyn region 3160 52.41 17.3 14.55 6.15 1.91 0.43 0.56 1.93 0.47 1.92 0.54 1.83000000000001
Dnipropetrovsk region 3140 44.72 9.43 6.28 6.26 10.53 4.74 5.15 2.68 3.22 0.82 1.12 5.05000000000001
Donezk region 3141 36.15 7.71 2.9 4.16 19.59 6.81 5.53 2.6 4.34 0.7 0.79 8.72
Zhytomyr region 3162 58.64 15.07 9.54 4.42 3.55 0.61 1.36 1.67 1.22 1.15 0.51 2.26000000000001
Zakarpattya region 3158 62.02 12.87 7.41 4.02 3.14 2.07 1.52 1.46 0.56 1.26 0.57 3.09999999999999
Zaporizhzhya region 3161 38.15 9.73 4.91 6.22 13.74 5.98 6.97 2.98 4.15 0.74 0.76 5.67000000000002
Ivano-Frankivsk region 3142 65.13 14.78 9.01 4.63 0.57 0.11 0.28 1.53 0.19 1.8 0.6 1.37
Kyiv region 3146 61.67 13.61 9.75 5.12 2.16 0.43 1.14 1.72 0.6 1.12 0.69 1.99000000000001
Kirovograd region 3148 50.96 16.15 11.55 5.83 4.09 1.32 2.03 1.92 1.5 1.39 0.49 2.76999999999998
Lugansk region 3149 33.17 7.77 6.17 4.55 15.74 8.02 5.89 2.41 5.43 0.78 0.41 9.66
Lviv region 3150 69.91 11.19 6.78 5.86 0.83 0.11 0.34 1.47 0.22 1.16 0.76 1.37
Mykolaiv region 3151 45.97 9.74 5.22 4.14 13.11 4.31 5.49 2.53 3.72 0.83 0.55 4.39
Odesa region 3152 41.78 9.48 3.58 2.93 18.57 3.85 6.18 2.6 3.83 0.9 0.67 5.63
Poltava region 3153 54.55 13.95 10.64 5.52 4.26 1.38 1.92 1.98 1.38 1.23 0.56 2.63
Rivne region 3154 55.46 16.06 13.23 5.04 2.1 0.28 0.76 2.1 0.56 1.69 0.69 2.03
Sumy region 3156 55.4 14.34 9.33 5.69 4.18 2.01 1.81 1.6 1.64 0.95 0.54 2.50999999999999
Ternopil region 3157 60.62 15.17 10.12 7.54 0.69 0.11 0.25 1.21 0.17 1.87 0.65 1.60000000000001
Kharkiv region 3143 35.28 7.64 3.92 4.42 8.54 26.25 3.82 2.14 2.65 0.61 0.75 3.98
Kherson region 3144 48.71 11.48 5.87 5.96 10.31 2.67 3.49 2.16 3.41 0.98 0.59 4.36999999999999
Khmelnyzky region 3145 56.26 16.95 11.82 4.73 2.05 0.6 0.87 1.71 0.77 1.64 0.5 2.09999999999999
Cherkasy region 3136 54.61 14.07 11.88 9.04 2.18 0.51 1.19 1.66 0.79 1.28 0.59 2.19999999999999
Chernivzi region 3138 56.72 18.84 10.5 3.12 2.7 0.43 1.09 1.46 0.75 1.26 0.54 2.59
Chernihiv region 3137 44.81 19.48 16.59 6.23 3.76 1.16 1.5 1.47 1.3 0.94 0.43 2.33000000000001
Kyiv City 3147 64.1 9.38 6.58 7 3.26 0.69 1.6 2.09 0.78 1.21 1.27 2.03999999999999
(function() {
d3.force_labels = function force_labels() {
var labels = d3.layout.force();
// Update the position of the anchor based on the center of bounding box
function updateAnchor() {
if (!labels.selection) return;
labels.selection.each(function(d) {
var bbox = this.getBBox(),
x = bbox.x + bbox.width / 2,
y = bbox.y + bbox.height / 2;
d.anchorPos.x = x;
d.anchorPos.y = y;
// If a label position does not exist, set it to be the anchor position
if (d.labelPos.x == null) {
d.labelPos.x = x;
d.labelPos.y = y;
}
});
}
//The anchor position should be updated on each tick
labels.on("tick.labels", updateAnchor);
// This updates all nodes/links - retaining any previous labelPos on updated nodes
labels.update = function(selection) {
labels.selection = selection;
var nodes = [], links = [];
selection[0].forEach(function(d) {
if(d && d.__data__) {
var data = d.__data__;
if (!d.labelPos) d.labelPos = {fixed: false};
if (!d.anchorPos) d.anchorPos = {fixed: true};
// Place position objects in __data__ to make them available through
// d.labelPos/d.anchorPos for different elements
data.labelPos = d.labelPos;
data.anchorPos = d.anchorPos;
links.push({target: d.anchorPos, source: d.labelPos});
nodes.push(d.anchorPos);
nodes.push(d.labelPos);
}
});
labels
.stop()
.nodes(nodes)
.links(links);
updateAnchor();
labels.start();
};
return labels;
};
})();
<!DOCTYPE html>
<meta charset="utf-8">
<title>Results of presidential election-2014 in Ukraine. Visualized by Texty.org.ua</title>
<style>
/* CSS goes here. */
body {
/* background-color: black; */
}
path{fill: lightgrey;}
.place{
fill: none;
}
.place_label{
fill: #444;
}
text{
fill: #666;
font-size: 10px;
stroke: none;
font-family: Liberation Sans Narrow;
font-family: Arial;
}
text.selected {
fill: #E31A1C;
}
.title text { font-size: 15px; font-weight: bold; }
text#oblname{ font-size: 10px;}
.monobar_names { font-weight: bold; }
.state-boundary {
fill: none;
stroke: #fff;
stroke-dasharray: 2,3;
stroke-linejoin: round;
stroke-width: 0.7px;
}
.r6-5 { fill: #B10026;}
.r5-5 { fill: #E31A1C;}
.r4-5 { fill: #FC4E2A;}
.r3-5 { fill: #FD8D3C;}
.r2-5 { fill: #FEB24C;}
.r1-5 { fill: #FED976;}
.r0-5 { fill: #FFFFB2;}
div.tooltip {
position: absolute;
text-align: left;
width: 100px;
height: 25px;
padding: 9px;
font: 12px sans-serif;
color: black;
background: #E6EAEB;
border: 0px;
border-radius: 8px;
pointer-events: none;
opacity: 0;
}
.monobar rect {fill-opacity: 0.7;}
.caption {
font-weight: bold;
}
.key path {
display: none;
}
.key line {
stroke: #000;
shape-rendering: crispEdges;
}
pattern#diagonalHatch1 path {
stroke: #FC4E2A;
stroke-width: 1px;
}
.voters rect{
fill: none;
stroke: white;
stroke-width: 1;
}
.turnout rect{
fill: white;
stroke: none;
fill-opacity: 0.5;
}
rect.voters_leg{
fill: none;
stroke: gray;
stroke-width: 0.5px;
}
rect.turnout_leg{
fill: gray;
opacity: 0.5;
stroke: none;
}
.turnout_legend line{
stroke: gray;
stroke-width: 0.5px;
}
.control{
position: absolute;
top: 46px;
left: 36px;
font-size: 10px;
font-family: Arial;
color: #666;
}
input.checkbox{
position: relative;
bottom: -4px;
padding: 0px;
margin: 0 0 10 -10px;
-ms-transform: scale(0.7); /* IE */
-moz-transform: scale(0.7); /* FF */
-webkit-transform: scale(0.7); /* Safari and Chrome */
-o-transform: scale(0.7); /* Opera */
padding: 10px;
}
</style>
<body>
<div class="tooltip"></div>
<div class="control"><input id="add_turnout" class="checkbox" type="checkbox" autocomplete="off"><label for="checkbox-1">Show turnout</label></div>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://d3js.org/queue.v1.min.js"></script>
<script src="https://d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="https://d3js.org/topojson.v0.min.js"></script>
<script src="simple-statistics.js"></script>
<script src="force_labels.js"></script>
<script src="turnout_data.js"></script>
<script>
/* JavaScript goes here. */
var width = 900,
height = 1000,
labels, current_name, global_data, geo_data, selected, path;
var data = {}, color_domain;
queue()
.defer(d3.json, "ua_topo_en.json")
.defer(d3.csv, "data_100_en.csv")
.await(ready);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// add pattern
svg.append('pattern')
.attr({
'id':'diagonalHatch1',
'patternUnits':"userSpaceOnUse",
'width':4,
'height':4,
//'patternTransform':"rotate(90 0 0)" could use rotate to make different pattern
})
.append('path')
.attr('d', "M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2");
var nested_turnout = d3.nest()
.key(function(d){return d.id;})
.map(turnout);
//console.log(nested_turnout);
var cand_names = [ 'Poroshenko', 'Tymoshenko', 'Lyashko', 'Grytzenko',
'Tigipko', 'Dobkin', 'Rabinovych', 'Bogomolez', 'Symonenko', 'Tyagnybok', 'Yarosh', 'Others'];
var full_names = { 'Poroshenko': 'Petro Poroshenko', 'Tymoshenko': 'Yulia Tymoshenko', 'Lyashko': 'Oleh Lyashko',
'Grytzenko': 'Anatolii Grytzenko', 'Tigipko': 'Serhij Tigipko', 'Dobkin': 'Myhailo Dobkin',
'Rabinovych': 'Vadym Rabinovych', 'Bogomolez': 'Olha Bogomolez', 'Symonenko': 'Petro Symonenko',
'Tyagnybok': 'Oleh Tyagnybok', 'Yarosh': 'Dmytro Yarosh', 'Others':'All others'};
// this is default results (Poroshenko)
var results = [54.7, 12.81, 8.32, 5.48, 5.23, 3.03, 2.25, 1.91, 1.51, 1.16, 0.7, 2.9];
results = cand_names.reduce(function(mem, d, i){ mem[d] = results[i]; return mem; }, {});
hor_monobar(results);
// add callback for checkbox
d3.select("#add_turnout")
.on('change', function(){ var selection = svg.select('g#map');
if(d3.select(this)[0][0].checked){
show_turnout( selection );
} else { hide_turnout( selection )};})
function ready(error, uk_geo_data, rows) {
var labelForce;
geo_data = uk_geo_data;
global_data = rows;
add_titles();
current_name = 'Poroshenko';
data = get_results(rows, current_name);
choropleth(data, uk_geo_data);
color_legend(data, current_name);
}
function add_titles(){
// titles
svg.append('g').attr('class', 'title')
.append('text')
.attr('x', 35)
.attr('y', 40)
.text('Map')
svg.append('text').attr('class', 'subtitle')
.attr('x', 35)
.attr('y', 100)
.text('(Hover on regions)')
var res = svg.append('g').attr('class', 'title');
res.append('text')
.attr('x', 680)
.attr('y', 40)
.text('Results')
res.append('text').attr('id', 'oblname')
.attr('x', 680)
.attr('y', 56)
.text('Ukraine: ' + d3.format(".2f")(results['Poroshenko']) + "%" )
}
function choropleth(data, geo_data){
color_domain = ss.jenks(d3.values(data), 5);
var scales = {};
scales.jenks7 = d3.scale.threshold()
.domain(color_domain)
.range(d3.range(8).map(function(i) { return "r" + i + "-5"; }));
var quantize = scales.jenks7;
var states = topojson.object(geo_data, geo_data.objects.states),
places = topojson.object(geo_data, geo_data.objects.mista);
var projection = d3.geo.albers()
.center([18, 42])
.rotate([-14, 0])
.parallels([30, 40])
.scale(2800)
.translate([width / 2 - 30, height / 2 + 70]);
path = d3.geo.path()
.projection(projection)
.pointRadius(2);
var map_cont = svg.selectAll('g#map')
.data([topojson.object(geo_data, geo_data.objects.states).geometries]);
map_cont.enter().append('g').attr('id', 'map')
.on("mouseout", reset_monobar );
var states = map_cont.selectAll(".states")
.data(function(d){return d;})
states.enter().append("path")
.attr("class", function(d) {return 'states' + ' ' + quantize(data[d.id]); })
.attr("d", path)
.on("mouseover", tooltip_on )
.on("mouseout", tooltip_off )
states
.attr("class", function(d) {return 'states' + ' ' + quantize(data[d.id]); });
var borders = map_cont.selectAll(".state-boundary")
.data([topojson.mesh(geo_data, geo_data.objects.states, function(a, b) { return a != b; })]);
borders.enter().append("path")
.attr("d", path)
.attr("class", "state-boundary");
var labelForce = d3.force_labels()
.linkDistance(5)
.gravity(0)
.charge(-5)
.alpha(0.99)
.nodes([]).links([])
.on("tick",function() { // redrow position of city names after force layout calculation
d3.selectAll(".place_label").attr("transform",function(d) {
return "translate("+(d.labelPos.x)+" "+(d.labelPos.y)+")"}) // labelPos - addition from force_labels
})
// add g containers and coomon data for text labels
var names = svg.selectAll('.place_label').remove();
var names = svg.selectAll('.names')
.data(places.geometries)
.enter().append('g');
names.append("path")
.attr("d", path)
.attr("class", "place")
.call(labelForce.update) // NOTE: key function for force_labels. this selection has been choosed
// as anchors for labels. update modifies labelPos and anchorPos for each element of selection.
// Due to common ancestor (names) both anchor nodes with 'path' and label nodes with 'text'
// have the same __data__ and thereafter labelPos and anchorPos
//.call(labelForce.drag);
// append text labels
names.append("text")
.attr("class", "place_label")
.attr("transform", function(d) {
return "translate(" + projection(d.coordinates) + ")"; })
.attr("dy", ".35em")
.attr("dx", ".45em")
.text(function(d) { return d.properties.name; });
}
// turnout vis
function hide_turnout(sel_root){
sel_root.selectAll(".voters").remove();
sel_root.selectAll(".turnout").remove();
sel_root.selectAll(".turnout_legend").remove();
}
function show_turnout(sel_root){
var map_cont = sel_root;
var sq_scale = d3.scale.sqrt()
.domain([600000, 3400000]).range([20, 50]);
var squares = map_cont.selectAll(".voters")
.data(function(d){return d;})
.enter().append('g').attr('class', 'voters');
squares.append('rect')
.attr("y", function(d){return path.centroid(d)[1] - sq_scale(nested_turnout[d.id][0].size)/2; })
.attr("x", function(d){ return path.centroid(d)[0] - sq_scale(nested_turnout[d.id][0].size)/2; } )
.attr("height", function(d){ return sq_scale(nested_turnout[d.id][0].size); } )
.attr("width", function(d){ return sq_scale(nested_turnout[d.id][0].size); } );
var fill_squares = map_cont.selectAll(".turnout")
.data(function(d){return d;})
.enter().append('g').attr('class', 'turnout');
var squares = fill_squares.append('rect')
.attr("y", function(d){return path.centroid(d)[1] - sq_scale(nested_turnout[d.id][0].size)/2; })
.attr("x", function(d){ return path.centroid(d)[0] - sq_scale(nested_turnout[d.id][0].size)/2; } )
.attr("height", function(d){ return sq_scale(nested_turnout[d.id][0].size); } )
.attr("width", 0 );
squares.transition().duration(1000)
.attr("width", function(d){ return sq_scale(nested_turnout[d.id][0].size) *
( nested_turnout[d.id][0].voted / nested_turnout[d.id][0].size) ; } );
// show turnout legend
var vert_shift = 390, hor_shift = 40;
var turnout_legend = map_cont.append('g').attr('class', 'turnout_legend');
turnout_legend.append('rect').attr('class', 'voters_leg')
.attr("y", vert_shift)
.attr("x", hor_shift )
.attr("height", sq_scale(1000000))
.attr("width", sq_scale(1000000));
turnout_legend.append('rect').attr('class', 'turnout_leg')
.attr("y", vert_shift)
.attr("x", hor_shift )
.attr("height", sq_scale(1000000))
.attr("width", sq_scale(1000000)/2);
turnout_legend.append('text').attr({x:hor_shift + 35, y:(vert_shift + 15)})
.text(' = 1 000 000 voters');
turnout_legend.append('text').attr({x:hor_shift+10, y:(vert_shift + 40)})
.text('turnout, %');
turnout_legend.append("line")
.attr({'y1': (vert_shift + sq_scale(1000000)),
'x1':(hor_shift + sq_scale(1000000)/4),
y2: (vert_shift + sq_scale(1000000)+15),
x2: hor_shift + sq_scale(1000000)/4});
}
function get_results(rows, key){
//var data = {};
rows.forEach(function(o){
o[key] = parseFloat(o[key]);
data[o.id] = o[key];
});
return data;
}
function reset_monobar(){
//d3.select('text#oblname').text('Україна');
d3.select('text#oblname').text('Ukraine' +': '+d3.format(".2f")(results[current_name]) + "%" );
hor_monobar(results);
}
function tooltip_off(o){
/* d3.select('.tooltip').transition()
.duration(500)
.style("opacity", 0);
*/
}
function tooltip_on(o) {
var divTooltip = d3.select('.tooltip');
var row;
var oblast_data = global_data.filter(function(d){
return o.id == d.id;
})
if(oblast_data = oblast_data[0]){
oblast_name = oblast_data.name;
oblast_data = cand_names.reduce(function(mem, d){ mem[d] = +oblast_data[d]; return mem; }, {});
// change oblast name in title
d3.select('text#oblname').text(oblast_name +': '+d3.format(".2f")(oblast_data[current_name])+"%");
// change highlight
hor_monobar(oblast_data);
/*
divTooltip.transition()
.duration(200)
.style("opacity", .9);
divTooltip.html(function(){return "<b>"+ current_name +": </b>" + oblast_data[current_name] + "%";} )
.style("left", function(){
var xc = d3.event.pageX;
return xc > width/2 ? (xc - 130) + "px" : (xc + 20) + "px";} )
.style("top", (d3.event.pageY - 50) + "px");
*/
}
}
function hor_monobar(results){
var bar_width = 380, bar_height = 20, leftpad = 680, toppad = 100, colors = ['#6baed6', '#deebf7'];
var compensators = [0, 0, 0, 0, 0, 0, 5, 9, 13, 17, 22, 27];
//summs[results.length - 1] = 100;
var res_data = cand_names.map(function(d, i){
return {name:d, result:results[d] /*, cumulative:summs[i] */};
});
var rizne = res_data.pop(); // pop out last value (Rizne value - sum all the other candidates)
res_data.sort(function(a, b){return b.result - a.result;} );
res_data.push(rizne);
// calculate increasing sum to find a position of next bar in stack
var summa = 0;
for(var i = 0; i < res_data.length; i++){
res_data[i]['cumulative'] = summa;
res_data[i]['comp'] = compensators[i];
summa += res_data[i]['result'];
};
var yscale = d3.scale.linear().domain([0, 100]).range([0, bar_width]);
// add barchart
var bars_group = svg.selectAll('g.monobar')
.data([res_data]);
bars_group.enter().append('g').attr('class', 'monobar');
var bars = bars_group.selectAll('rect')
.data(function(d){ return d;});
// initial run
bars.enter().append("rect")
.attr('fill', function(d, i){ if(i%2 == 0){ return "url(#diagonalHatch"+ (i%2+1) +")"}
else{return '#FC4E2A';}
;})
//.attr("fill", function(d, i){ return colors[i%2]; })
//.attr('class', function(d, i){ return 'pattern' + i%2; })
.attr("y", function(d){ return toppad + yscale(d.cumulative); })
.attr("x", leftpad )
.attr("height", function(d){ return yscale(d.result); } )
.attr("width", bar_height);
// if update needed
bars.transition()
.attr("y", function(d){ return toppad + yscale(d.cumulative); })
.attr("height", function(d){ return yscale(d.result); } );
var contenders_group = svg.selectAll('g.monobar_names')
.data([res_data]);
contenders_group.enter().append('g').attr('class', 'monobar_names');
var contenders = contenders_group.selectAll('text')
.data(function(d){ return d;}, function(d){return d.name;});
contenders.enter().append("text")
.text(function(d, i){ return d.name /* + ', ' + d.result + '%' */; })
.attr('class', function(d,i){if(i == 0){ return 'selected'; }})
.attr("y", function(d){ return -25 + toppad + yscale(d.cumulative + d.result/2) + d.comp; })
.attr("x", leftpad + 40 )
.on("click", function(d){
current_name = d.name;
d3.select('text#oblname').text('Ukraine' +': '+d.result + '%');
selected = d3.select(this);
d3.selectAll('g.monobar_names text').classed('selected', false);
d3.select(this).classed('selected', true).attr('id', d.name);
change_map(d);
})
.on("mouseover", function(d){ d3.select(this).classed('selected', true); })
.on("mouseout", function(d){
d3.select(this).classed('selected', false);
if(selected){ selected.classed('selected', true)} });
contenders.transition()
.attr("y", function(d){ return -25 + toppad + yscale(d.cumulative + d.result/2) + d.comp; })
.text(function(d, i){ return d.name; })
// tip
contenders_group.selectAll('text.tip')
.data(['click', 'on name'])
.enter().append('text').attr('class', 'tip')
.attr("y", function(d, i){ return toppad + 5 + i*10; })
.attr("x", leftpad + 40 )
.style("font-weight", 'normal')
.text(function(d){return d;})
// 0 and 100% ticks
var ticks = svg.selectAll('g.monobar_ticks')
.data([1])
.enter().append('g').attr('class', 'monobar_ticks');
ticks.selectAll("text")
.data([100, 0])
.enter().append("text")
.text(function(d, i){ return d + '%'; })
.attr("y", function(d){ return toppad + yscale(100-d) + (d == 0 ? -5 : 5); })
.attr("x", leftpad -30 )
var linepointers = svg.selectAll("line")
.data(res_data);
linepointers.enter().append("svg:line")
.attr("stroke", "gray")
.attr('stroke-dasharray', '3,2')
.style("stroke-width", 0.5)
.attr("x1", leftpad + 20)
.attr("y1", function(d){ return toppad + yscale(d.cumulative + d.result/2);} )
.attr("x2", leftpad + 38)
.attr("y2", function(d){ return -30 + toppad + yscale(d.cumulative + d.result/2) + d.comp;} );
linepointers.transition()
.attr("x1", leftpad + 20)
.attr("y1", function(d){ return toppad + yscale(d.cumulative + d.result/2);} )
.attr("x2", leftpad + 38)
.attr("y2", function(d){ return -30 + toppad + yscale(d.cumulative + d.result/2) + d.comp;} );
}
function change_map(d){
current_name = d.name; // glbal
var data = get_results(global_data, current_name);
choropleth(data, geo_data);
color_legend(data, current_name);
}
// @results must be from [0, 1] interval
function color_legend(data, name){
var legend_width = 250;
var color_domain = ss.jenks(d3.values(data), 5);
function formatFunction(d){
if(d <= 0.01){
return d3.format(".1f");
}
if( d >= 0.05){
return d3.format(".0f");
}
return d3.format(".1f");
}
var threshold = d3.scale.threshold()
.domain(color_domain.map(function(d){return d/100;}))
.range([ '#FFFFB2', '#FED976','#FEB24C','#FD8D3C','#FC4E2A','#E31A1C', '#B10026']);
var tmp = color_domain.pop()/100;
var max = tmp + 0.3*tmp;
// A position encoding for the key only.
var x = d3.scale.linear()
.domain([0, max])
.range([0, legend_width ]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(13)
.tickValues(threshold.domain())
.tickFormat(function(d) {
return formatFunction(d)(d*100) });
//clean
d3.select('g.key').remove();
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(" + 40 + "," + (height / 2 - 25) + ")");
g.selectAll("rect")
.data(threshold.range().map(function(color) {
var d = threshold.invertExtent(color);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().append("rect")
.attr("height", 8)
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.style("fill", function(d) { return threshold(d[0]); });
g.call(xAxis).append("text")
.attr("class", "caption")
.attr("y", -6)
.text("% of votes for a candidate" + ' (' + full_names[name] + ')');
}
</script>
// # simple-statistics
//
// A simple, literate statistics system. The code below uses the
// [Javascript module pattern](http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth),
// eventually assigning `simple-statistics` to `ss` in browsers or the
// `exports object for node.js
(function() {
var ss = {};
if (typeof module !== 'undefined') {
// Assign the `ss` object to exports, so that you can require
// it in [node.js](http://nodejs.org/)
exports = module.exports = ss;
} else {
// Otherwise, in a browser, we assign `ss` to the window object,
// so you can simply refer to it as `ss`.
this.ss = ss;
}
// # [Linear Regression](http://en.wikipedia.org/wiki/Linear_regression)
//
// [Simple linear regression](http://en.wikipedia.org/wiki/Simple_linear_regression)
// is a simple way to find a fitted line
// between a set of coordinates.
ss.linear_regression = function() {
var linreg = {},
data = [];
// Assign data to the model. Data is assumed to be an array.
linreg.data = function(x) {
if (!arguments.length) return data;
data = x.slice();
return linreg;
};
// ## Fitting The Regression Line
//
// This is called after `.data()` and returns the
// equation `y = f(x)` which gives the position
// of the regression line at each point in `x`.
linreg.line = function() {
//if there's only one point, arbitrarily choose a slope of 0
//and a y-intercept of whatever the y of the initial point is
if (data.length == 1) {
m = 0;
b = data[0][1];
} else {
// Initialize our sums and scope the `m` and `b`
// variables that define the line.
var sum_x = 0, sum_y = 0,
sum_xx = 0, sum_xy = 0,
m, b;
// Gather the sum of all x values, the sum of all
// y values, and the sum of x^2 and (x*y) for each
// value.
//
// In math notation, these would be SS_x, SS_y, SS_xx, and SS_xy
for (var i = 0; i < data.length; i++) {
sum_x += data[i][0];
sum_y += data[i][1];
sum_xx += data[i][0] * data[i][0];
sum_xy += data[i][0] * data[i][1];
}
// `m` is the slope of the regression line
m = ((data.length * sum_xy) - (sum_x * sum_y)) /
((data.length * sum_xx) - (sum_x * sum_x));
// `b` is the y-intercept of the line.
b = (sum_y / data.length) - ((m * sum_x) / data.length);
}
// Return a function that computes a `y` value for each
// x value it is given, based on the values of `b` and `a`
// that we just computed.
return function(x) {
return b + (m * x);
};
};
return linreg;
};
// # [R Squared](http://en.wikipedia.org/wiki/Coefficient_of_determination)
//
// The r-squared value of data compared with a function `f`
// is the sum of the squared differences between the prediction
// and the actual value.
ss.r_squared = function(data, f) {
if (data.length < 2) return 1;
// Compute the average y value for the actual
// data set in order to compute the
// _total sum of squares_
var sum = 0, average;
for (var i = 0; i < data.length; i++) {
sum += data[i][1];
}
average = sum / data.length;
// Compute the total sum of squares - the
// squared difference between each point
// and the average of all points.
var sum_of_squares = 0;
for (var j = 0; j < data.length; j++) {
sum_of_squares += Math.pow(average - data[j][1], 2);
}
// Finally estimate the error: the squared
// difference between the estimate and the actual data
// value at each point.
var err = 0;
for (var k = 0; k < data.length; k++) {
err += Math.pow(data[k][1] - f(data[k][0]), 2);
}
// As the error grows larger, it's ratio to the
// sum of squares increases and the r squared
// value grows lower.
return 1 - (err / sum_of_squares);
};
// # [Bayesian Classifier](http://en.wikipedia.org/wiki/Naive_Bayes_classifier)
//
// This is a naïve bayesian classifier that takes
// singly-nested objects.
ss.bayesian = function() {
// The `bayes_model` object is what will be exposed
// by this closure, with all of its extended methods, and will
// have access to all scope variables, like `total_count`.
var bayes_model = {},
// The number of items that are currently
// classified in the model
total_count = 0,
// Every item classified in the model
data = {};
// ## Train
// Train the classifier with a new item, which has a single
// dimension of Javascript literal keys and values.
bayes_model.train = function(item, category) {
// If the data object doesn't have any values
// for this category, create a new object for it.
if (!data[category]) data[category] = {};
// Iterate through each key in the item.
for (var k in item) {
var v = item[k];
// Initialize the nested object `data[category][k][item[k]]`
// with an object of keys that equal 0.
if (data[category][k] === undefined) data[category][k] = {};
if (data[category][k][v] === undefined) data[category][k][v] = 0;
// And increment the key for this key/value combination.
data[category][k][item[k]]++;
}
// Increment the number of items classified
total_count++;
};
// ## Score
// Generate a score of how well this item matches all
// possible categories based on its attributes
bayes_model.score = function(item) {
// Initialize an empty array of odds per category.
var odds = {}, category;
// Iterate through each key in the item,
// then iterate through each category that has been used
// in previous calls to `.train()`
for (var k in item) {
var v = item[k];
for (category in data) {
// Create an empty object for storing key - value combinations
// for this category.
if (odds[category] === undefined) odds[category] = {};
// If this item doesn't even have a property, it counts for nothing,
// but if it does have the property that we're looking for from
// the item to categorize, it counts based on how popular it is
// versus the whole population.
if (data[category][k]) {
odds[category][k + '_' + v] = (data[category][k][v] || 0) / total_count;
} else {
odds[category][k + '_' + v] = 0;
}
}
}
// Set up a new object that will contain sums of these odds by category
var odds_sums = {};
for (category in odds) {
// Tally all of the odds for each category-combination pair -
// the non-existence of a category does not add anything to the
// score.
for (var combination in odds[category]) {
if (odds_sums[category] === undefined) odds_sums[category] = 0;
odds_sums[category] += odds[category][combination];
}
}
return odds_sums;
};
// Return the completed model.
return bayes_model;
};
// # sum
//
// is simply the result of adding all numbers
// together, starting from zero.
//
// This runs on `O(n)`, linear time in respect to the array
ss.sum = function(x) {
var sum = 0;
for (var i = 0; i < x.length; i++) {
sum += x[i];
}
return sum;
};
// # mean
//
// is the sum over the number of values
//
// This runs on `O(n)`, linear time in respect to the array
ss.mean = function(x) {
// The mean of no numbers is null
if (x.length === 0) return null;
return ss.sum(x) / x.length;
};
// # geometric mean
//
// a mean function that is more useful for numbers in different
// ranges.
//
// this is the nth root of the input numbers multipled by each other
//
// This runs on `O(n)`, linear time in respect to the array
ss.geometric_mean = function(x) {
// The mean of no numbers is null
if (x.length === 0) return null;
// the starting value.
var value = 1;
for (var i = 0; i < x.length; i++) {
// the geometric mean is only valid for positive numbers
if (x[i] <= 0) return null;
// repeatedly multiply the value by each number
value *= x[i];
}
return Math.pow(value, 1 / x.length);
};
// Alias this into its common name
ss.average = ss.mean;
// # min
//
// This is simply the minimum number in the set.
//
// This runs on `O(n)`, linear time in respect to the array
ss.min = function(x) {
var min;
for (var i = 0; i < x.length; i++) {
// On the first iteration of this loop, min is
// undefined and is thus made the minimum element in the array
if (x[i] < min || min === undefined) min = x[i];
}
return min;
};
// # max
//
// This is simply the maximum number in the set.
//
// This runs on `O(n)`, linear time in respect to the array
ss.max = function(x) {
var max;
for (var i = 0; i < x.length; i++) {
// On the first iteration of this loop, min is
// undefined and is thus made the minimum element in the array
if (x[i] > max || max === undefined) max = x[i];
}
return max;
};
// # [variance](http://en.wikipedia.org/wiki/Variance)
//
// is the sum of squared deviations from the mean
ss.variance = function(x) {
// The variance of no numbers is null
if (x.length === 0) return null;
var mean = ss.mean(x),
deviations = [];
// Make a list of squared deviations from the mean.
for (var i = 0; i < x.length; i++) {
deviations.push(Math.pow(x[i] - mean, 2));
}
// Find the mean value of that list
return ss.mean(deviations);
};
// # [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation)
//
// is just the square root of the variance.
ss.standard_deviation = function(x) {
// The standard deviation of no numbers is null
if (x.length === 0) return null;
return Math.sqrt(ss.variance(x));
};
ss.sum_squared_deviations = function(x) {
// The variance of no numbers is null
if (x.length <= 1) return null;
var mean = ss.mean(x),
sum = 0;
// Make a list of squared deviations from the mean.
for (var i = 0; i < x.length; i++) {
sum += Math.pow(x[i] - mean, 2);
}
return sum;
};
// # [variance](http://en.wikipedia.org/wiki/Variance)
//
// is the sum of squared deviations from the mean
ss.sample_variance = function(x) {
var sum_squared_deviations = ss.sum_squared_deviations(x);
if (sum_squared_deviations === null) return null;
// Find the mean value of that list
return sum_squared_deviations / (x.length - 1);
};
// # [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation)
//
// is just the square root of the variance.
ss.sample_standard_deviation = function(x) {
// The standard deviation of no numbers is null
if (x.length <= 1) return null;
return Math.sqrt(ss.sample_variance(x));
};
// # [covariance](http://en.wikipedia.org/wiki/Covariance)
//
// sample covariance of two datasets:
// how much do the two datasets move together?
// x and y are two datasets, represented as arrays of numbers.
ss.sample_covariance = function(x, y) {
// The two datasets must have the same length which must be more than 1
if (x.length <= 1 || x.length != y.length){
return null;
}
// determine the mean of each dataset so that we can judge each
// value of the dataset fairly as the difference from the mean. this
// way, if one dataset is [1, 2, 3] and [2, 3, 4], their covariance
// does not suffer because of the difference in absolute values
var xmean = ss.mean(x),
ymean = ss.mean(y),
sum = 0;
// for each pair of values, the covariance increases when their
// difference from the mean is associated - if both are well above
// or if both are well below
// the mean, the covariance increases significantly.
for (var i = 0; i < x.length; i++){
sum += (x[i] - xmean) * (y[i] - ymean);
}
// the covariance is weighted by the length of the datasets.
return sum / (x.length - 1);
};
// # [correlation](http://en.wikipedia.org/wiki/Correlation_and_dependence)
//
// Gets a measure of how correlated two datasets are, between -1 and 1
ss.sample_correlation = function(x, y) {
var cov = ss.sample_covariance(x, y),
xstd = ss.sample_standard_deviation(x),
ystd = ss.sample_standard_deviation(y);
if (cov === null || xstd === null || ystd === null) {
return null;
}
return cov / xstd / ystd;
};
// # [median](http://en.wikipedia.org/wiki/Median)
ss.median = function(x) {
// The median of an empty list is null
if (x.length === 0) return null;
// Sorting the array makes it easy to find the center, but
// use `.slice()` to ensure the original array `x` is not modified
var sorted = x.slice().sort(function (a, b) { return a - b; });
// If the length of the list is odd, it's the central number
if (sorted.length % 2 === 1) {
return sorted[(sorted.length - 1) / 2];
// Otherwise, the median is the average of the two numbers
// at the center of the list
} else {
var a = sorted[(sorted.length / 2) - 1];
var b = sorted[(sorted.length / 2)];
return (a + b) / 2;
}
};
// # [mode](http://bit.ly/W5K4Yt)
// This implementation is inspired by [science.js](https://github.com/jasondavies/science.js/blob/master/src/stats/mode.js)
ss.mode = function(x) {
// Handle edge cases:
// The median of an empty list is null
if (x.length === 0) return null;
else if (x.length === 1) return x[0];
// Sorting the array lets us iterate through it below and be sure
// that every time we see a new number it's new and we'll never
// see the same number twice
var sorted = x.slice().sort(function (a, b) { return a - b; });
// This assumes it is dealing with an array of size > 1, since size
// 0 and 1 are handled immediately. Hence it starts at index 1 in the
// array.
var last = sorted[0],
// store the mode as we find new modes
mode,
// store how many times we've seen the mode
max_seen = 0,
// how many times the current candidate for the mode
// has been seen
seen_this = 1;
// end at sorted.length + 1 to fix the case in which the mode is
// the highest number that occurs in the sequence. the last iteration
// compares sorted[i], which is undefined, to the highest number
// in the series
for (var i = 1; i < sorted.length + 1; i++) {
// we're seeing a new number pass by
if (sorted[i] !== last) {
// the last number is the new mode since we saw it more
// often than the old one
if (seen_this > max_seen) {
max_seen = seen_this;
seen_this = 1;
mode = last;
}
last = sorted[i];
// if this isn't a new number, it's one more occurrence of
// the potential mode
} else { seen_this++; }
}
return mode;
};
// # [t-test](http://en.wikipedia.org/wiki/Student's_t-test)
//
// This is to compute a one-sample t-test, comparing the mean
// of a sample to a known value, x.
//
// in this case, we're trying to determine whether the
// population mean is equal to the value that we know, which is `x`
// here. usually the results here are used to look up a
// [p-value](http://en.wikipedia.org/wiki/P-value), which, for
// a certain level of significance, will let you determine that the
// null hypothesis can or cannot be rejected.
ss.t_test = function(sample, x) {
// The mean of the sample
var sample_mean = ss.mean(sample);
// The standard deviation of the sample
var sd = ss.standard_deviation(sample);
// Square root the length of the sample
var rootN = Math.sqrt(sample.length);
// Compute the known value against the sample,
// returning the t value
return (sample_mean - x) / (sd / rootN);
};
// # quantile
// This is a population quantile, since we assume to know the entire
// dataset in this library. Thus I'm trying to follow the
// [Quantiles of a Population](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population)
// algorithm from wikipedia.
//
// Sample is a one-dimensional array of numbers,
// and p is a decimal number from 0 to 1. In terms of a k/q
// quantile, p = k/q - it's just dealing with fractions or dealing
// with decimal values.
ss.quantile = function(sample, p) {
// We can't derive quantiles from an empty list
if (sample.length === 0) return null;
// invalid bounds. Microsoft Excel accepts 0 and 1, but
// we won't.
if (p >= 1 || p <= 0) return null;
// Sort a copy of the array. We'll need a sorted array to index
// the values in sorted order.
var sorted = sample.slice().sort(function (a, b) { return a - b; });
// Find a potential index in the list. In Wikipedia's terms, this
// is I<sub>p</sub>.
var idx = (sorted.length) * p;
// If this isn't an integer, we'll round up to the next value in
// the list.
if (idx % 1 !== 0) {
return sorted[Math.ceil(idx) - 1];
} else if (sample.length % 2 === 0) {
// If the list has even-length and we had an integer in the
// first place, we'll take the average of this number
// and the next value, if there is one
return (sorted[idx - 1] + sorted[idx]) / 2;
} else {
// Finally, in the simple case of an integer value
// with an odd-length list, return the sample value at the index.
return sorted[idx];
}
};
// Compute the matrices required for Jenks breaks. These matrices
// can be used for any classing of data with `classes <= n_classes`
ss.jenksMatrices = function(data, n_classes) {
// in the original implementation, these matrices are referred to
// as `LC` and `OP`
//
// * lower_class_limits (LC): optimal lower class limits
// * variance_combinations (OP): optimal variance combinations for all classes
var lower_class_limits = [],
variance_combinations = [],
// loop counters
i, j,
// the variance, as computed at each step in the calculation
variance = 0;
// Initialize and fill each matrix with zeroes
for (i = 0; i < data.length + 1; i++) {
var tmp1 = [], tmp2 = [];
for (j = 0; j < n_classes + 1; j++) {
tmp1.push(0);
tmp2.push(0);
}
lower_class_limits.push(tmp1);
variance_combinations.push(tmp2);
}
for (i = 1; i < n_classes + 1; i++) {
lower_class_limits[1][i] = 1;
variance_combinations[1][i] = 0;
// in the original implementation, 9999999 is used but
// since Javascript has `Infinity`, we use that.
for (j = 2; j < data.length + 1; j++) {
variance_combinations[j][i] = Infinity;
}
}
for (var l = 2; l < data.length + 1; l++) {
// `SZ` originally. this is the sum of the values seen thus
// far when calculating variance.
var sum = 0,
// `ZSQ` originally. the sum of squares of values seen
// thus far
sum_squares = 0,
// `WT` originally. This is the number of
w = 0,
// `IV` originally
i4 = 0;
// in several instances, you could say `Math.pow(x, 2)`
// instead of `x * x`, but this is slower in some browsers
// introduces an unnecessary concept.
for (var m = 1; m < l + 1; m++) {
// `III` originally
var lower_class_limit = l - m + 1,
val = data[lower_class_limit - 1];
// here we're estimating variance for each potential classing
// of the data, for each potential number of classes. `w`
// is the number of data points considered so far.
w++;
// increase the current sum and sum-of-squares
sum += val;
sum_squares += val * val;
// the variance at this point in the sequence is the difference
// between the sum of squares and the total x 2, over the number
// of samples.
variance = sum_squares - (sum * sum) / w;
i4 = lower_class_limit - 1;
if (i4 !== 0) {
for (j = 2; j < n_classes + 1; j++) {
if (variance_combinations[l][j] >=
(variance + variance_combinations[i4][j - 1])) {
lower_class_limits[l][j] = lower_class_limit;
variance_combinations[l][j] = variance +
variance_combinations[i4][j - 1];
}
}
}
}
lower_class_limits[l][1] = 1;
variance_combinations[l][1] = variance;
}
return {
lower_class_limits: lower_class_limits,
variance_combinations: variance_combinations
};
};
// # [Jenks natural breaks optimization](http://en.wikipedia.org/wiki/Jenks_natural_breaks_optimization)
//
// Implementations: [1](http://danieljlewis.org/files/2010/06/Jenks.pdf) (python),
// [2](https://github.com/vvoovv/djeo-jenks/blob/master/main.js) (buggy),
// [3](https://github.com/simogeo/geostats/blob/master/lib/geostats.js#L407) (works)
ss.jenks = function(data, n_classes) {
// sort data in numerical order
data = data.slice().sort(function (a, b) { return a - b; });
// get our basic matrices
var matrices = ss.jenksMatrices(data, n_classes),
// we only need lower class limits here
lower_class_limits = matrices.lower_class_limits,
k = data.length - 1,
kclass = [],
countNum = n_classes;
// the calculation of classes will never include the upper and
// lower bounds, so we need to explicitly set them
kclass[n_classes] = data[data.length - 1];
kclass[0] = data[0];
// the lower_class_limits matrix is used as indexes into itself
// here: the `k` variable is reused in each iteration.
while (countNum > 1) {
kclass[countNum - 1] = data[lower_class_limits[k][countNum] - 2];
k = lower_class_limits[k][countNum] - 1;
countNum--;
}
return kclass;
};
// # Mixin
//
// Mixin simple_statistics to the Array native object. This is an optional
// feature that lets you treat simple_statistics as a native feature
// of Javascript.
ss.mixin = function() {
var support = !!(Object.defineProperty && Object.defineProperties);
if (!support) throw new Error('without defineProperty, simple-statistics cannot be mixed in');
// only methods which work on basic arrays in a single step
// are supported
var arrayMethods = ['median', 'standard_deviation', 'sum',
'mean', 'min', 'max', 'quantile', 'geometric_mean'];
// create a closure with a method name so that a reference
// like `arrayMethods[i]` doesn't follow the loop increment
function wrap(method) {
return function() {
// cast any arguments into an array, since they're
// natively objects
var args = Array.prototype.slice.apply(arguments);
// make the first argument the array itself
args.unshift(this);
// return the result of the ss method
return ss[method].apply(ss, args);
};
}
// for each array function, define a function off of the Array
// prototype which automatically gets the array as the first
// argument. We use [defineProperty](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty)
// because it allows these properties to be non-enumerable:
// `for (var in x)` loops will not run into problems with this
// implementation.
for (var i = 0; i < arrayMethods.length; i++) {
Object.defineProperty(Array.prototype, arrayMethods[i], {
value: wrap(arrayMethods[i]),
configurable: true,
enumerable: false,
writable: true
});
}
};
})(this);
var turnout = [
{"name":"Севастополь","id":3155,"size":308913,"voted":0,"turnout":0.00},
{"name":"Крим","id":3139,"size":1531366,"voted":0,"turnout":0.00},
{"name":"Вінницька","id":3159,"size":1288320,"voted":895219,"turnout":0.69},
{"name":"Волинська","id":3160,"size":786151,"voted":581796,"turnout":0.74},
{"name":"Дніпропетровська","id":3140,"size":2682704,"voted":1465119,"turnout":0.55},
{"name":"Донецька","id":3141,"size":3352382,"voted":115823,"turnout":0.03},
{"name":"Житомирська","id":3162,"size":1006913,"voted":659335,"turnout":0.65},
{"name":"Закарпатська","id":3158,"size":960799,"voted":486273,"turnout":0.51},
{"name":"Запорізька","id":3161,"size":1459980,"voted":735764,"turnout":0.50},
{"name":"Івано-Франківська","id":3142,"size":1079634,"voted":796008,"turnout":0.74},
{"name":"Київська","id":3146,"size":1469520,"voted":996046,"turnout":0.68},
{"name":"Кіровоградська","id":3148,"size":784129,"voted":467755,"turnout":0.60},
{"name":"Луганська","id":3149,"size":1797379,"voted":52239,"turnout":0.03},
{"name":"Львівська","id":3150,"size":1978675,"voted":1544016,"turnout":0.78},
{"name":"Миколаївська","id":3151,"size":932477,"voted":472522,"turnout":0.51},
{"name":"Одеська","id":3152,"size":1828788,"voted":836659,"turnout":0.46},
{"name":"Полтавська","id":3153,"size":1196316,"voted":761748,"turnout":0.64},
{"name":"Рівненська","id":3154,"size":874777,"voted":614771,"turnout":0.70},
{"name":"Сумська","id":3156,"size":930964,"voted":570645,"turnout":0.61},
{"name":"Тернопільська","id":3157,"size":855900,"voted":650087,"turnout":0.76},
{"name":"Харківська","id":3143,"size":2182068,"voted":1033847,"turnout":0.47},
{"name":"Херсонська","id":3144,"size":865456,"voted":439332,"turnout":0.51},
{"name":"Хмельницька","id":3145,"size":1052597,"voted":728864,"turnout":0.69},
{"name":"Черкаська","id":3136,"size":1041065,"voted":673734,"turnout":0.65},
{"name":"Чернівецька","id":3138,"size":706236,"voted":431758,"turnout":0.61},
{"name":"Чернігівська","id":3137,"size":873774,"voted":557295,"turnout":0.64},
{"name":"м.Київ","id":3147,"size":2174016,"voted":1380005,"turnout":0.63}];
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment