Skip to content

Instantly share code, notes, and snippets.

@nivas8292
Last active August 29, 2015 14:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nivas8292/5bab3efa0310171940ec to your computer and use it in GitHub Desktop.
Force Layout - Charge

All the Nodes are assigned with Negative charges.

All but the bigger Node have same negative charge. The Bigger node has a bigger negative charge and so it repels more.

Try to drag the bigger node nearer to other nodes

<html>
<head>
<title>D3 Force Layout Charge Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
</head>
<body>
<script>
var w = 800;
var h = 450;
var margin = {
top: 20,
bottom: 20,
left: 20,
right: 20
};
var width = w - margin.left - margin.right;
var height = h - margin.top - margin.bottom;
var svg = d3.select("body")
.append("svg")
.attr("id", "chart")
.attr("height", h)
.attr("width", w);
var colorScale = d3.scale.category20();
var nodes = [15, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10].map(function (d) {
return {"radius": d};
});
var force = d3.layout.force()
.nodes(nodes)
.size([w, h])
.charge(function (d, i) {
return (i == 0) ? -1000 : -100;
})
.on("tick", tick)
.start();
var circles = svg.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r", function (d) {
return d.radius;
})
.style("fill", function (d, i) {
return colorScale(i);
})
.call(force.drag);
function tick() {
circles
.attr("cx", function (d) {
return d.x;
})
.attr("cy", function (d) {
return d.y;
});
}
</script>
</body>
</html>
body, html {
margin:0;
padding:0;
font-family:"Arial", sans-serif;
font-size:0.95em;
text-align:center;
}
#chart {
background-color:#F5F2EB;
border: 1px solid #CCC;
}
.bar {
fill:purple;
shape-rendering:crispEdges;
}
.bar-label {
text-anchor:end;
fill:white;
}
.axis path,
.axis line {
fill:none;
stroke:#000;
shape-rendering:crispEdges;
}
.gridline path,
.gridline line {
fill: none;
stroke: #ccc;
shape-rendering: crispEdges;
}
.trendline {
fill: none;
stroke: #ccc;
stroke-width: 2;
/*stroke-dasharray:10;*/
}
.area {
fill: #ccc;
stroke: #ccc;
opacity: 0.25;
}
.donut {
opacity:0.1;
}
.axis-label {
text-anchor: middle;
}
.chart-header {
text-transform: capitalize;
font-size: 110%;
}
.temperature {
stroke:#95cddf;
stroke-width:2px;
}
.rain {
fill:none;
stroke:#cc627a;
stroke-width:0.5;
}
#cursor {
stroke: black;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment