D3's force layout with CSS sprites

Size
11,951 Kb
Views
52,624

How do I make an d3's force layout with css sprites?

This graph shows the correlation between best position on world cup versus number of participation, GDP (PIB), population, HDI (IDH) and number of world cups participation. What is a d3's force layout with css sprites? How do you make a d3's force layout with css sprites? This script and codes were developed by Rafael Abensur on 12 September 2022, Monday.

D3's force layout with CSS sprites Previews

D3's force layout with CSS sprites - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>D3's force layout with CSS sprites</title> <script src="https://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel='stylesheet prefetch' href='https://cloud.github.com/downloads/lafeber/world-flags-sprite/flags32.css'>
<link rel='stylesheet prefetch' href='css/9a5ecf2380448bc1a0825a3cb.css'> <link rel="stylesheet" href="css/style.css">
</head>
<body> <main class="wrapper">
<div class="align-center"> <form class="inline-radio-group" id="x-axis-menu"> <input id="Sede" name="copa" type="radio" /> <label for="Sede">Sede</label> <input checked="true" id="Participações" name="copa" type="radio" /> <label for="Participações">Participa&ccedil;&otilde;es</label> <input id="PIB" name="copa" type="radio" /> <label for="PIB">PIB</label> <input id="População" name="copa" type="radio" /> <label for="População">Popula&ccedil;&atilde;o</label> <input id="IDH" name="copa" type="radio" /> <label for="IDH">IDH</label></form>
</div>
<div class="g-container image-container">&nbsp;</div>
</main>
<pre id="data">
Pais,Participações,Melhor Posição,Posição Mídia,Sede,PIB,População,IDH,Codigo
Alemanha,17,1,4,2,3635959000,80716000,0.92,de
França,13,1,10,2,2737361000,65885000,0.893,fr
Inglaterra,13,1,7,1,2535761000,53012456,0.875,_England
Brasil,19,1,5,1,2242854000,201032714,0.73,br
Itália,17,1,7,2,2071955000,60021955,0.881,it
Espanha,13,1,9,1,1358687000,46609700,0.885,es
Argentina,15,1,7,1,488213000,42669500,0.811,ar
Uruguai,11,1,9,1,56345000,3286314,0.792,uy
Holanda,9,2,7,0.0001,800007000,16848300,0.921,nl
Suécia,11,2,9,1,557938000,9658301,0.916,se
República Checa,9,2,10,0.0001,198312000,10512400,0.873,cz
Hungria,9,2,9,0.0001,132426000,9879000,0.831,hu
Estados Unidos,9,3,16,1,16799700000,317951000,0.937,us
Turquia,2,3,6,0.0001,827209000,76667864,0.722,tr
Polônia,7,3,12,0.0001,516128000,38507281,0.821,pl
Áustria,7,3,11,0.0001,415366000,8504850,0.895,at
Chile,8,3,11,1,276975000,17620000,0.819,cl
Portugal,5,3,11,0.0001,219972000,10477800,0.816,pt
Croácia,3,3,16,0.0001,58058000,4290612,0.805,balta
Rússia,9,4,11,0.0001,2118006000,143700000,0.788,ru
Coreia do Sul,8,4,18,1,1221801000,50219669,0.909,kr
Bélgica,10,4,12,0.0001,506560000,11190649,0.897,be
Bulgária,7,4,15,0.0001,53046000,7245677,0.782,bg
Sérvia,11,4,11,0.0001,42525000,7181505,0.769,rs
Suíça,9,5,11,1,650814000,8136700,0.913,ch
México,14,6,12,2,1258544000,119713203,0.775,mx
Romênia,7,6,10,0.0001,189659000,20121641,0.786,ro
País de Gales,1,6,6,0.0001,79530000,3063456,0.875,_Wales
Peru,4,7,11,0.0001,206542000,30475144,0.741,pe
Gana,2,7,10,0.0001,44223000,24658823,0.558,gh
Camarões,6,7,20,0.0001,27957000,20386799,0.495,cm
Senegal,1,7,7,0.0001,15154000,12873601,0.47,sn
Dinamarca,4,8,13,0.0001,330958000,5627235,0.901,dk
Irlanda,3,8,12,0.0001,217884000,4593100,0.916,ie
Ucrânia,1,8,8,0.0001,176235000,45395604,0.74,ua
Cuba,1,8,8,0.0001,60810000,11167325,0.78,cu
Coréia do Norte,2,8,20,0.0001,40000000,24895000,0.733,mf
Irlanda do Norte,3,8,13,0.0001,37330000,1810863,0.875,_Northern_Ireland
Paraguai,8,8,13,0.0001,28333000,6783374,0.669,py
Nigéria,4,9,19,0.0001,286470000,173615000,0.471,ng
Japão,4,9,19,1,4901532000,127140000,0.912,jp
Escócia,8,9,16,0.0001,235000000,5313600,0.875,_Scotland
Tunísia,4,9,22,0.0001,47439000,10886500,0.712,tn
Marrocos,4,11,17,0.0001,105101000,33244100,0.591,ma
Arábia Saudita,4,12,25,0.0001,745273000,29994272,0.782,sa
Noruega,3,12,15,0.0001,511252000,5109056,0.955,no
Israel,1,12,12,0.0001,291500000,8157300,0.9,il
Equador,2,12,18,0.0001,94144000,15729100,0.724,ec
CostaRica,3,12,21,0.0001,49621000,4667096,0.773,cr
Bolívia,3,12,15,0.0001,29802000,10027254,0.675,bo
Egipto,2,13,17,0.0001,271427000,86368000,0.662,eg
Argélia,3,13,21,0.0001,206095000,38700000,0.713,dz
Austrália,3,14,17,0.0001,1505277000,23467130,0.938,au
Colômbia,4,14,17,0.0001,381822000,47568000,0.719,co
Irã,3,14,20,0.0001,366259000,77393000,0.742,ir
Haiti,1,15,15,0.0001,8458000,10413211,0.456,ht
Eslováquia,1,16,16,0.0001,95805000,5415949,0.84,sk
El Salvador,2,16,20,0.0001,24512000,6340000,0.68,sv
Congo,1,16,16,0.0001,13781000,67514000,0.534,cd
África do Sul,3,17,20,1,350779000,52981991,0.629,za
Costa do Marfim,2,17,18,0.0001,28288000,23202000,0.432,ci
Eslovênia,2,18,24,0.0001,46851000,2062436,0.892,si
Honduras,2,18,24,0.0001,18813000,8555072,0.632,hn
Kuwait,1,21,21,0.0001,185319000,3065850,0.79,kw
Nova Zelândia,2,22,23,0.0001,181330000,4526370,0.919,nz
Jamaica,1,22,22,0.0001,14288000,2711476,0.73,jm
Iraque,1,23,23,0.0001,229327000,34035000,0.59,iq
Angola,1,23,23,0.0001,121704000,20609294,0.508,ao
Canadá,1,24,24,0.0001,1825096000,35344962,0.911,ca
Emirados Árabes Unidos,1,24,24,0.0001,396235000,8264070,0.818,ae
Grécia,2,24,25,0.0001,241796000,10815197,0.86,gr
Trinidad e Tobago,1,27,27,0.0001,27703000,1328019,0.76,tt
Togo,1,30,30,0.0001,4360000,6191155,0.459,tg
China,1,31,31,0.0001,9181377000,1364150000,0.699,cn
</pre> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script> <script src="js/index.js"></script>
</body>
</html>

D3's force layout with CSS sprites - Script Codes CSS Codes

* { box-sizing: border-box; }
.axis path, pre#data{ display:none; }
.label, .axis{ font-family: $font-light; font-size:smaller; fill: $gray-80;
}
.axis path,
.axis line { fill:none; stroke:#000; shape-rendering:crispEdges;
}
.tick line{ stroke: $gray-20; stroke-width:1;
}
.grid .tick{ stroke: $gray-20; }
.grid line{ stroke-width:.5; }
.dot:hover{ cursor:pointer; }
.flag{ position:absolute; transform:scale(.6);
}
.g-container{ position: relative;
}
.g-dados{ width: 85%; margin: 0 auto; display: flex;
}
.g-dados .flag-name { flex: 3; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; text-align: center; font-family: $font-bold;
}
.g-dados .flag-name .flag{ position: relative; display: block; margin: 10px auto 0; transform: scale(1.1);
}
.g-dados .flag-name span:not(.flag){ font-family: $font-bold;
}
.g-dados .all-data { flex: 6; display: flex; flex-flow: row wrap;
}
.g-dados .all-data div { flex: 0 50%; padding: 2px 3px;
}
.g-dados .all-data div span:first-child{ font-size: .875rem; font-family: $font; margin-right: 10px; float: left;
}
.g-dados .all-data div span:last-child{ font-size: .9375rem; font-family: $font-medium; float: right;
}
.inline-radio-group { border-radius: 5px; display: inline-block; border: 1px solid $gray-30; // display: inline-block extra margin // http://stackoverflow.com/a/8262649/1736417 font-size: 0px; label { font-family: $font; color: $gray-50; cursor: pointer; display: inline-block; border-radius: 5px; font-size: .875rem; line-height: .875rem; padding-top: .4375rem; padding-left: .8125rem; padding-right: .8125rem; padding-bottom: .4375rem; transition: .3s background; } input { width: 0; height: 0; opacity: 0; appearance: none; &:focus { outline: 0; outline-offset: 0; } } input:checked+label{ color: white; font-family: $font; background: $blue; box-shadow: 0 0 0 1px $blue; }
}
.wrapper { margin: 20px auto 0; text-align: center; max-width: 680px;
}

D3's force layout with CSS sprites - Script Codes JS Codes

// Parse Numbers to Float - https://prcweb.co.uk/lab/what-makes-us-happy/
function parseData(d) { 'use strict'; var keys = _.keys(d[0]); return _.map(d, function(d) { var o = {}; _.each(keys, function(k) { if( k == 'Pais' || k == 'Codigo') // Prevent Strings Being Parsed o[k] = d[k]; else o[k] = parseFloat(d[k]); }); return o; });
}
// Find min and maxes (for the scales)
function getBounds(d, paddingFactor) { paddingFactor = typeof paddingFactor !== 'undefined' ? paddingFactor : 1; var keys = _.keys(d[0]), b = {}; _.each(keys, function(k) { b[k] = {}; _.each(d, function(d) { if(isNaN(d[k])) return; if(b[k].min === undefined || d[k] < b[k].min) b[k].min = d[k]; if(b[k].max === undefined || d[k] > b[k].max) b[k].max = d[k]; }); b[k].max > 0 ? b[k].max *= paddingFactor : b[k].max /= paddingFactor; b[k].min > 0 ? b[k].min /= paddingFactor : b[k].min *= paddingFactor; }); return b;
}
// Force-Directed Scatterplot
// Source: https://bl.ocks.org/rpgove/10603627
var data = d3.csv.parse( d3.select("pre#data").text() );
'use strict';
// Resolve collisions between nodes.
function collide(alpha) { var quadtree = d3.geom.quadtree(data); return function (d) { var r = d.radius + radius + 5, nx1 = d.x - r, nx2 = d.x + r, ny1 = d.y - r, ny2 = d.y + r; quadtree.visit(function (quad, x1, y1, x2, y2) { if (quad.point && (quad.point !== d)) { var qx = d.x - quad.point.x, qy = d.y - quad.point.y, l = Math.sqrt(qx * qx + qy * qy), qr = d.radius + quad.point.radius + (d.color !== quad.point.color); if (l < qr) { l = (l - qr) / l * alpha; qx = qx * l; qy = qy * l; d.x = d.x - qx; d.y = d.y - qy; quad.point.x += qx; quad.point.y += qy; } } return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1; }); };
}
function moveTowardDataPosition(alpha) { return function (d) { d.x += (xScale(d[xVar]) - d.x) * 0.1 * alpha; d.y += (y(d[yVar]) - d.y) * 0.1 * alpha; };
}
function tick(e) { node.each(moveTowardDataPosition(e.alpha)); node.each(collide(e.alpha, false)); node .attr("cx", function (d) { return d.x; }) .attr("cy", function (d) { return d.y; }); flags .attr('style', function (d) { var styleString; styleString = 'top:'; styleString += d.y + 68; styleString += 'px; left: '; styleString += d.x + 25; styleString += 'px;'; return styleString; });
}
data = parseData(data);// Parse numbers to Float
var xVar = "Participações", yVar = "Melhor Posição", xVarOptions = [ "Sede", "Participações", "PIB", "População", "IDH" ], descriptions = { "População" : "População", "Host" : "Quantas vezes sediou uma copa do mundo", "PIB" : "PIB", "Participações" : "Número de participações em copas", "IDH": "IDH" }, //empty for changing xScale xScale, // Gets max and min bounds = getBounds(data, 1), formatValue = d3.format(".2s"), // Change tick format value thisTickFormat = function (d) { return formatValue(d).replace('G', 'B'); }, margin = {top: 20, right: 20, bottom: 20, left: 20}, padding = margin, outerWidth = $('.wrapper').width(), outerHeight = 400, innerWidth = outerWidth - margin.left - margin.right, innerHeight = outerHeight - margin.top - margin.bottom, width = innerWidth - padding.left - padding.right, height = innerHeight - padding.top - padding.bottom, radius = 10, //x axis scale x = d3.scale.log().base(2).range([0, width]), // y axis scale y = d3.scale.log().base(2).range([0, height]), // Declare Axis xAxis = d3.svg.axis() .scale(x) .orient("bottom") .tickFormat(thisTickFormat), yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(d3.format("d")), force, node, flags, // Dom Elements container, circles, svg, dl, span;
// THE CREATION
// Create the Container
container = d3.select(".g-container");
// Create the SVG
svg = container .append("svg") .attr("width", outerWidth) .attr("height", outerHeight);
svg.append("g").attr("class", "g-circles") .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
circles = svg.select("g").append("g");
// Create the nodes
node = circles.selectAll(".dot") .data(data) .enter() .append("circle") .attr("class", "dot") .attr("r", radius) .attr("cx", function (d) { return x(d[xVar]); }) .attr("cy", function (d) { return y(d[yVar]); }) .style("fill", function (d) { return 'transparent'; });
// Create the viz.
var viz = container .insert("div", ':first-child') .attr("class", "g-dados");
var flagName = viz.append('div') .attr("class", "f32 flag-name");
var allData = viz.append('div') .attr("class", "all-data");
// Create THE FORCE
force = d3.layout.force() .nodes(data) // .links(data) .size([innerWidth, innerHeight]) .on("tick", tick) .charge(20) .gravity(0) .chargeDistance(20);
// Create the Visualization
flagName.append("span").attr("class", "flag br");
flagName.append("span").text("Brasil");
var dataMelhorPosicao = allData.append('div').attr('data-type', 'Melhor Posição');
dataMelhorPosicao.append('span').text("Melhor Posição");;
dataMelhorPosicao.append('span').attr("class", "first-dado").text("1º Lugar");
var dataSede = allData.append('div').attr('data-type', 'Sede');
dataSede.append('span').text("Melhor Posição");;
dataSede.append('span').text("1 vez");
var dataParticipacoes = allData.append('div').attr('data-type', 'Participações');
dataParticipacoes.append('span').text("Participações");;
dataParticipacoes.append('span').text("19");
var dataPIB = allData.append('div').attr('data-type', 'PIB');
dataPIB.append('span').text("PIB (US$)");;
dataPIB.append('span').text("2.2B");
var dataPopulacao = allData.append('div').attr('data-type', 'População');
dataPopulacao.append('span').text("População");;
dataPopulacao.append('span').text("200M");
var dataIDH = allData.append('div').attr('data-type', 'IDH');
dataIDH.append('span').text("IDH");;
dataIDH.append('span').text("0.730");
// Create the Flags
flags = container.append('div') .attr("class", "g-flags") .append("ul") .attr('class', 'f32') .selectAll("li") .data(force.nodes()) .enter().append('li') .attr('class', function (d) { return 'flag ' + d.Codigo; }) .on("mouseover", function (d) { d3.select('.flag-name span:last-child') .html(d.Pais); d3.select('.flag-name .flag') .attr('class', 'flag ' + d.Codigo); d3.select(".all-data div[data-type='Melhor Posição'] span:last-child") .html(d["Melhor Posição"] + "º Lugar"); d3.select(".all-data div[data-type='Sede'] span:last-child") .html(d.Sede === 1 ? d.Sede + " vez" : (d.Sede < 2 ? "Nunca" : d.Sede + " vezes")); d3.select(".all-data div[data-type='Participações'] span:last-child") .html(d["Participações"]); formatValue = d3.format(".2s"); var thisFormatValue = function (d) { return formatValue(d).replace('G', 'B'); }; d3.select(".all-data div[data-type='PIB'] span:last-child") .html(thisFormatValue(d.PIB)); d3.select(".all-data div[data-type='População'] span:last-child") .html(thisFormatValue(d["População"])); formatValue = d3.format(".3f"); d3.select(".all-data div[data-type='IDH'] span:last-child") .html(formatValue(d.IDH)); });
// Set scale domain
x.domain(d3.extent(data, function (d) { return d[xVar]; })).nice();
y.domain(d3.extent(data, function (d) { return d[yVar]; })).nice();
// Set initial positions
data.forEach(function (d) { d.x = x(d[xVar]); d.y = y(d[yVar]); d.radius = radius;
});
// Create the x Axis Menu
d3.select('#x-axis-menu') .selectAll('label') .on('click', function (d) { force.stop(); xVar = d3.select(this).attr('for'); updateChart(); updateMenus();
});
// Render axes
svg.append("g") .attr("class", "x axis") .attr("transform", "translate(40," + (height + 28) + ")") .call(xAxis);
svg.append("g") .attr("class", "y axis") .attr('transform', 'translate(40, 20)') .call(yAxis) .append("text");
function makeXAxis(s) { s.call(d3.svg.axis() .scale(xScale) .orient("bottom") .tickSize(-height - 7, 0, 0) .tickFormat(thisTickFormat));
}
function makeYAxis(s) { s.call(d3.svg.axis() .scale(y) .orient("left") .tickSize(-width, 0, 0) .tickFormat(function (d) { return d + "º"; }));
}
function updateScales() { switch (xVar) { case "População": //Country population formatValue = d3.format(".2s"); thisTickFormat = function (d) { return formatValue(d).replace('G', 'B'); }; xScale = d3.scale.log().base(2) .range([0, width]) .domain(d3.extent(data, function (d) { return d[xVar]; })).nice(); break; case "Sede": //How many times this country hosted a world cup formatValue = d3.format("d"); xScale = d3.scale.linear() .range([0, width]) .domain([bounds[xVar].min, bounds[xVar].max]); break; case "PIB": // GDP - Gross Domestic Product formatValue = d3.format(".2s"); xScale = d3.scale.log().base(2) .range([0, width]) .domain([bounds[xVar].min, bounds[xVar].max]); break; case "Participações": // How many times this country went to a world cup formatValue = d3.format("d"); xScale = d3.scale.linear() .range([0, width]) .domain([bounds[xVar].min, bounds[xVar].max]); break; case "IDH": formatValue = d3.format(".2f"); xScale = d3.scale.linear() .range([0, width]) .domain([bounds[xVar].min, bounds[xVar].max]); break; }
}
function updateChart() { updateScales(); d3.selectAll('.dot') .transition() .duration(1000) .ease('quad-out') .attr('cx', function (d) { return xScale(d[xVar]); }) .attr('cy', function (d) { return y(d[yVar]); }); //Also update the axes d3.select('.x') .transition() .call(makeXAxis); d3.select('.y') .transition() .call(makeYAxis); // Update axis labels d3.select('.label') .text(descriptions[xVar]); // Start THE FORCE force.start();
}
function updateMenus() { d3.select('#x-axis-menu') .selectAll('a') .classed('active', function (d) { return d === xVar; });
}
updateChart();
updateMenus();
D3's force layout with CSS sprites - Script Codes
D3's force layout with CSS sprites - Script Codes
Home Page Home
Developer Rafael Abensur
Username abensur
Uploaded September 12, 2022
Rating 4
Size 11,951 Kb
Views 52,624
Do you need developer help for D3's force layout with CSS sprites?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Rafael Abensur (abensur) Script Codes
Create amazing love letters with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!