Example illustrating the use of both d3-force-attract
and d3-force-cluster
.
forked from ericsoco's block: d3-force-cluster + d3-force-attract I
xxxxxxxxxx
<html>
<head>
<title>d3-force-cluster and d3-force-attract</title>
</head>
<style>
/*tooltip*/
.tooltip {
background-color: #333;
padding: 4px 8px;
position: absolute;
color: #fff;
opacity: 0.8;
z-index: 100;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3.legend.js"></script>
<script src="https://unpkg.com/d3-force-attract@latest"></script>
<script src="https://unpkg.com/d3-force-cluster@latest"></script>
<script src="https://cdn.jsdelivr.net/gh/exupero/savesvgaspng/gh-pages/savesvgaspng.js"></script>
<p>Grafica</p>
<div id="motivos-rechazo">
</div>
<button class="btn btn-primary" onclick="svgToPng()">svg to png</button>
<script>
var datos = [
{motivo: "Emp", frequency: 10},
{motivo: "Pro", frequency: 1},
{motivo: "Can", frequency: 3},
{motivo: "No", frequency: 4},
{motivo: "Cli", frequency: 5},
{motivo: "Epa", frequency: 6},
{motivo: "Prd", frequency: 7},
{motivo: "Cie", frequency: 8},
{motivo: "Ent", frequency: 9},
{motivo: "Noh", frequency: 9},
{motivo: "Cen", frequency: 9},
{motivo: "Otros", frequency: 9}
];
var width = 500,
height = 350,
padding = 1.5, // separation between same-color nodes
clusterPadding = 0, // separation between different-color nodes
maxRadius = 50;
minRadius = 5;
contador = 0;
var n = datos.length, // total number of nodes
m = 20; // number of distinct clusters
var salto = function() {
if ( maxRadius/n > minRadius)
return Math.floor(maxRadius/n);
else
return minRadius;
}
var color = d3.scaleLinear().domain([0,1])
.interpolate(d3.interpolateHcl)
.range([d3.rgb("#EBEBFF"), d3.rgb('#0000FF')]);
// The largest node for each cluster.
var clusters = new Array(m);
var nodes = d3.range(n).map(function () {
var i = Math.floor(Math.random() * m),
i1 = contador,
r = Math.sqrt((i + 1) / m * -Math.log(Math.random())) * maxRadius,
r1 = datos[contador]["frequency"],
r2 = function () {
if(n == 1) {
return salto();
}
var actual = datos[contador]["frequency"];
var maximo = function() {
if (datos[0]["frequency"] > 0)
return datos[0]["frequency"];
else
return 1;
};
//datos[0]["frequency"];
var relacion = Math.floor(actual * maxRadius / maximo());
if (relacion <= salto())
return minRadius;
return (relacion);
},
degrade = function () {
var actual = datos[contador]["frequency"];
var maximo = datos[0]["frequency"];
var relacion = Math.floor(actual * n / maximo);
return relacion;
},
d = {
cluster: i1,
degrade: degrade(),
radius: r2(),
nombre: datos[contador]["motivo"],
frecuencia: datos[contador]["frequency"],
x: Math.cos(i1 / m * 2 * Math.PI) * 200 + width / 2 + Math.random(),
y: Math.sin(i1 / m * 2 * Math.PI) * 200 + height / 2 + Math.random()
};
contador++;
if (!clusters[i1] || (r2 > clusters[i1].radius)) clusters[i1] = d;
return d;
});
var simulation = d3.forceSimulation()
// keep entire simulation balanced around screen center
.force('center', d3.forceCenter(width/2, height/2))
// pull toward center
.force('attract', d3.forceAttract()
.target([width/2, height/2])
.strength(0.1))
// cluster by section
.force('cluster', d3.forceCluster()
.centers(function (d) { return clusters[d.cluster]; })
.strength(0.5)
.centerInertia(0.1))
// apply collision with padding
.force('collide', d3.forceCollide(function (d) { return d.radius + padding; })
.strength(0))
.on('tick', layoutTick)
.nodes(nodes);
var tooltip = d3.select("#motivos-rechazo").append("div")
.attr("class", "tooltip");
var svg = d3.select('#motivos-rechazo').append('svg')
.attr('width', width)
.attr('height', height);
var node = svg.selectAll('circle')
.data(nodes)
.enter()
.append('circle')
.style('fill', function (d) { return color(d.degrade/n); })
.attr('id', function (d) { return d.nombre + ": " + d.frecuencia; })
.call(d3.drag()
.on('start', dragstarted)
.on('drag', dragged)
.on('end', dragended)
)
.on('mouseover', function(d){
d3.select("#major").text(d.key);
tooltip.transition()
.duration(500)
.style("opacity", 1);
tooltip.html( this.id )
.style("left", (d3.event.pageX - 25) + "px")
.style("top", (d3.event.pageY - 50) + "px");
})
.on('mousemove', function (d) {
tooltip.style("top", (d3.event.pageY - 50) + 'px');
tooltip.style("left", (d3.event.pageX - 25) + 'px');
})
.on('mouseout', function(d){
d3.select("#major").text("Mouse over");
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
var margin = {top: 50, right: 50, bottom: 50, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.bottom - margin.top;
svg.append("text")
.attr("class", "title")
.attr("x", (width/4))
.attr("y", 20)
.text("Porcentaje de las entregas según su estado");
function dragstarted (d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged (d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended (d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
// ramp up collision strength to provide smooth transition
var transitionTime = 3000;
var t = d3.timer(function (elapsed) {
var dt = elapsed / transitionTime;
simulation.force('collide').strength(Math.pow(dt, 2) * 0.7);
if (dt >= 1.0) t.stop();
});
function layoutTick (e) {
node
.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; })
.attr('r', function (d) { return d.radius; })
.attr('text', function (d) { return d.nombre; });
}
function svgToPng() {
saveSvgAsPng(d3.select('svg').node(), 'chart.png');
}
</script>
</body>
</html>
Updated missing url https://rawgit.com/exupero/saveSvgAsPng/gh-pages/saveSvgAsPng.js to https://cdn.jsdelivr.net/gh/exupero/savesvgaspng/gh-pages/savesvgaspng.js
https://d3js.org/d3.v4.min.js
https://unpkg.com/d3-force-attract@latest
https://unpkg.com/d3-force-cluster@latest
https://rawgit.com/exupero/saveSvgAsPng/gh-pages/saveSvgAsPng.js