xxxxxxxxxx
<meta charset="utf-8">
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
d3.csv("data.csv", function(error, data) {
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
// "Electric repulsive charge", prevents overlap of nodes
var chargeForce = d3.forceManyBody()
// Keep nodes centered on screen
var centerXForce = d3.forceX(width / 2);
var centerYForce = d3.forceY(height / 2);
// Apply default forces to simulation
var simulation = d3.forceSimulation()
.force("charge", chargeForce)
.force("x", centerXForce)
.force("y", centerYForce);
var node = svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("r", 10)
.attr("fill", "#777");
// Add the nodes to the simulation, and specify how to draw
simulation.nodes(data)
.on("tick", function() {
// The d3 force simulation updates the x & y coordinates
// of each node every tick/frame, based on the various active forces.
// It is up to us to translate these coordinates to the screen.
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
// Interaction with button
var splitState = false;
document.getElementById("split-button").onclick = function() {
if(!splitState) {
// Turn off charge, let the nodes overlap
simulation.force("charge", null);
} else {
// Turn on charge, nodes should "pop" out
simulation.force("charge", chargeForce);
}
// Toggle state
splitState = !splitState;
// NOTE: Very important to call both alphaTarget AND restart in conjunction
// Restart by itself will reset alpha (cooling of simulation)
// but won't reset the velocities of the nodes (inertia)
simulation.alpha(1).restart();
};
});
</script>
<style>
html {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}
#split-button{
position: absolute;
bottom: 10px;
right: 10px;
padding: 10px 20px;
font-size: 2em;
text-align: center;
background: #FFF;
border-radius: 5px;
border: 1px solid #DDD;
}
#split-button:hover {
background: #CCC;
cursor: pointer;
}
</style>
<body>
<div id="split-button">Toggle "Charge"</div>
<svg width="960" height="500"></svg>
</body>
https://d3js.org/d3.v4.min.js