This is not a true Dorling cartogram; it lacks links between adjacent features. Instead of trying to preserve connectedness, this pseudo-cartogram tries to preserve locality, putting each circle as close as possible to its origin without overlapping.
forked from mbostock's block: Pseudo-Dorling Cartogram
forked from AminaSGitHub's block: babylone_P22222
forked from AminaSGitHub's block: babylone_P1_Transition
xxxxxxxxxx
<meta charset="utf-8">
<title>Dorling Cartogram</title>
<style>
circle {
fill: #eee;
stroke: #000;
stroke-width: 1.5px;
}
h1 {
text-align : center;
}
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg {
position: relative;
left: 30px;
border: 3px solid #B0E0E6;
}
.province {
fill: #000;
stroke: #fff;
stroke-width: 1px;
}
.province:hover {
opacity: 0.5;
}
.Node{
fill: #000;
stroke: black;
stroke-width: 2px;
}
.Node:hover{
opacity: 0.5;
}
.hiddenN {
display: none;
}
div.tooltipN {
color: #222;
background-color: #fff;
padding: .5em;
text-shadow: #f5f5f5 0 1px 0;
border-radius: 2px;
opacity: 0.9;
position: absolute;
}
.hidden {
display: none;
}
div.tooltip {
color: #222;
background-color: #fff;
padding: .5em;
text-shadow: #f5f5f5 0 1px 0;
border-radius: 2px;
opacity: 0.9;
position: absolute;
}
</style>
<body>
<div>
<input id="sliderYear" type="range" value="1" min="1" max="5" step="1" />
<span id="year">year </span>
</div>
<div>
<input id="slider" type="range" value="1" min="1" max="12" step="1" />
<span id="month">month </span>
</div>
<div>
<span >Nœud </span>
<input id="sliderType" type="range" value="1" min="1" max="2" step="1" />
<span >Carte </span>
</div>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
// On definie une echelle de couleur
var color = d3.scaleQuantize()
.range(["rgb(213,239,204)",
"rgb(169,221,160)",
"rgb(94,186,97)",
"rgb(42,141,71)",
"rgb(0,91,36)"]);
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
padding = 3;
var projection = d3.geoConicConformal().center([2.454071, 46.279229]).scale(2000);
var path = d3.geoPath() // d3.geo.path avec d3 version 3
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var pas,minG,maxG;
var nbrColors = 5;
d3.csv("TER_France2013_2017.csv", function(data) {
d3.json("regions.json", function(error, states) {
if (error) throw error;
var jsonF;
var listDates = Object.keys(data[0]);
var listYears = []; // Will contain [2013,2014,2015,2016]
var listMonths = []; // Will contain [Janvier,...,Decembre]
var currentYear = 1; //"2013";
var currentMonth = 1; //" Janvier";
/*Begin legend*/
var element;
minG = parseFloat(Object.values(data[0])[1]);
maxG = parseFloat(Object.values(data[0])[1]);
for (var i = 0; i < data.length; i++) {
for(var j = 1; j < listDates.length-4; j++){
//console.log("ELEMENT : ===> data : "+Object.values(data[i])[j]);
element = parseFloat(Object.values(data[i])[j]);
if (element < minG ){
minG = element;
}
if (element > maxG ){
maxG = element;
}
}
}
// console.log("MAX = : "+maxG + " MIN = : "+ minG);
color.domain([ minG,maxG ]);
pas = (maxG - minG)/nbrColors;
//console.log("Pas "+ pas);
drawLegende(minG, maxG,pas);
/*End legend*/
var radius = d3.scaleSqrt()
.domain([0,parseFloat(maxG)])
.range([0, 35]);
for(var m = 1; m< listDates.length; m++){
var datee = listDates[m].split(" ");
if (listYears.findIndex(p => p == datee[1]) === (-1)) {
listYears.push(datee[1]);
}
if (listMonths.findIndex(p => p == datee[0]) === (-1)) {
if(datee[0] != "Somme2013" && datee[0] != "Somme2014" && datee[0] != "Somme2015" && datee[0] != "Somme2016" && datee[0] != "Somme2017"){
listMonths.push(datee[0]);
}
}
}
var first = listDates[1].split(" ");
// first value for sliderYear
var firstYear = listYears[0];
var firstMonth = listMonths[0];
//d3.select('#month').html(first[0]);
d3.select('#month').html(firstMonth);
d3.select('#year').html(firstYear);
// update the month in slider
d3.select("#slider").on("input", function() {
//currentMonth = listMonths[this.value-1];
currentMonth = +this.value;
updateViz(+this.value);
});
d3.select("#sliderYear").on("input", function() {
currentYear = +this.value;
updateViz2(+this.value);
});
//On fusionne les donnees avec le GeoJSON des regions
for (var i = 0; i < data.length; i++) {
// Find the name of the region in csv file
var dataState = data[i].region;
//console.log("DataState : " + dataState )
for (var j = 0; j< states.features.length; j++){
// Find the name of the region in json file
var jsonState = states.features[j].properties.nom;//
if (dataState == jsonState) {
states.features[j].properties.tab = Object.values(data[i]);
//stop because result found
break;
}
}
}
jsonF = states;
var currentViz =1;
d3.select("#sliderType").on("input", function() {
currentViz = +this.value;
console.log("CurrentViz = ==========> "+currentViz);
if(currentViz == 1){
drawNodes(currentMonth, currentYear);
}else{
drawMap(currentMonth, currentYear);
}
});
if(currentViz == 1){
drawNodes(currentMonth, currentYear);
}else{
drawMap(currentMonth, currentYear);
}
//update elements
function updateViz(val){
d3.select('#month').html(listMonths[val-1]);
if(currentViz == 1){
drawNodes(currentMonth, currentYear);
}else{
drawMap(currentMonth, currentYear);
}
};
function updateViz2(valY){
d3.select('#year').html(listYears[valY-1]);
if(currentViz == 1){
drawNodes(currentMonth, currentYear);
}else{
drawMap(currentMonth, currentYear);
}
};
var carte;
function drawMap(monthBis, yearBis){
var tooltip = d3.select('body')
.append('div')
.attr('class', 'hidden tooltip');
svg.selectAll("circle").remove();
console.log("JE SUIS DANS DRAW MAP");
svg.selectAll("path")
.data(states.features)
.enter()
.append("path")
.attr("d", path);
var nbr;
var currentDate = 12*(yearBis-1)+monthBis ;
//fevrier 2017 => 2017 = 5 fevrier 2 ====> 12*(yearBis-1)+monthBis
// console.log("cu rrentDate ==========> " + currentDate);
//Set input domain for color scale
color.domain([ minG,maxG]);
carte = svg.selectAll("path")
.data(jsonF.features);
carte
.on('mousemove', function(d) {
if(d.properties.tab == undefined || d.properties.tab == "NaN"){
nbr = "undefined";
}else {
nbr = d.properties.tab[currentDate];
}
var mouse = d3.mouse(svg.node()).map(function(d) {
return parseInt(d);
});
tooltip.classed('hidden', false)
.attr('style', 'left:' + (mouse[0] + 15) +
'px; top:' + (mouse[1] - 35) + 'px')
.html(d.properties.nom + ":" + parseFloat(nbr).toFixed(2)+ " %");
})
.on('mouseout', function() {
tooltip.classed('hidden', true);
});
//code in case of update of the map / change of month
carte
.attr('class', function(d) {
return 'province ' + d.properties.code;
})
.attr('d', path)
.style("fill", function(d) {
// get value found above
var tab = d.properties.tab;
if (tab && tab[currentDate] != "") {
// console.log("tabbbbb ==>" + tab[currentDate]);
return color(tab[currentDate]);
} else {
// if no value then color with Grey
return "#ccc";
}
});
//fist time of coloring the map
carte.selectAll("path")
.enter()
.data(jsonF.features)
.append("path")
.attr("class", "enter")
.attr("d", path)
.style("fill", function(d) {
// get value found above
var tab = d.properties.tab;
console.log("tabbbb ==>" + tab[currentDate]);
if (tab && tab[currentDate] != "") {
return color(tab[currentDate]);
} else {
// if no value then color with Grey
return "#ccc";
}
});
}; // End of drawMap//
function drawNodes(monthBis, yearBis){
console.log("JE SUIS DANS DRAW NODES");
svg.selectAll('path').remove();
svg.selectAll('circle').remove();
var currentDate = 12*(yearBis-1)+monthBis ;
var c = color;
var nbr;
var nodes = states.features
.map(function(d) {
if (d.properties.tab == undefined){
nbr="undefined";
}else {
nbr=d.properties.tab[currentDate];
}
if(d.geometry.coordinates[0][0].length === 2){
console.log("size = 2");
var point = projection(d.geometry.coordinates[0][0]),
value = nbr;
}else{
//console.log("size > 2");
var point = projection(d.geometry.coordinates[0][0][0]),
value = nbr;
}
var rayon;
if(nbr=="undefined"){
rayon =20;
}else {
rayon = value;
}
return {
x: point[0], y: point[1],
x0: point[0], y0: point[1],
r: radius(rayon) ,
value: value,
region: d.properties.nom
};
});
// console.log("NBR NODES "+nodes.length);
var force = d3.forceSimulation(nodes)
.force('charge',d3.forceManyBody())
.force('x', d3.forceX(width/2).strength(0.005))
.force('y', d3.forceY(height/2).strength(0.005));
// .force("collide", d3.forceCollide().strength(0.000000000000000005));
var tooltipN = d3.select('body')
.append('div')
.attr('class', 'hiddenN tooltipN');
var node = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", function(d) { return d.r; })
.attr('class', function(d) {
return 'Node ' + d.code;
})
.on("mouseover", function(d){
var mouse = d3.mouse(svg.node()).map(function(d) {
return parseInt(d);
});
tooltipN.classed('hiddenN', false)
.attr('style', 'left:' + (mouse[0] + 15) +
'px; top:' + (mouse[1] - 35) + 'px')
.html(d.region + " : "+d.value);
})
.on('mouseout', function() {
tooltipN.classed('hiddenN', true);
})
.style("fill", function(d) {
// get value found above
var tab = d.value;
if (tab && d.value != "undefined") {
// console.log("tabbbbb ==>" + d.value);
return c(d.value);
} else {
// if no value then color with Grey
return "#ccc";
}
});
force
.nodes(nodes)
.on("tick", tick);
//.restart(); ///
function tick(e) {
//console.log( d3.select(this));
node.each(gravity(force.alpha() * .1))
.each(collide(.5))
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
function gravity(k) {
return function(d) {
d.x += (d.x0 - d.x) * k;
d.y += (d.y0 - d.y) * k;
};
}
function collide(k) {
var q = d3.quadtree().addAll(nodes);
return function(node) {
var nr = node.r + padding,
nx1 = node.x - nr,
nx2 = node.x + nr,
ny1 = node.y - nr,
ny2 = node.y + nr;
q.visit(function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = x * x + y * y,
r = nr + quad.point.r;
if (l < r * r) {
l = ((l = Math.sqrt(l)) - r) / l * k;
node.x -= x *= l;
node.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
});
};
}
}
}); // End of "regions.json"
/*Function to add legende */
function drawLegende(min, max,pas){
var c = color;
var limites = [];
c.domain([min,max]);
//console.log("limites Avant : "+ limites);
var bool;
for(var it=min; it<max; it = it+pas){
limites.push(it);
}
//console.log("limites Apres : "+ limites);//
var legend = svg.selectAll(".legend")
.data(limites)
.enter()
.append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + i * 20 + ")";
});
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", function(d) { return color(d); });
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { var dPas = d+ pas;return parseFloat(d).toFixed(2) + " %-" + parseFloat(dPas).toFixed(2)+ " %" ; });
}
}); //End of CSV File
</script>
https://d3js.org/d3.v4.min.js