Skip to content

Instantly share code, notes, and snippets.

@maegul
Last active October 28, 2017 12:18
Show Gist options
  • Save maegul/24c44f9d7bdd1372e015401c247ff836 to your computer and use it in GitHub Desktop.
Save maegul/24c44f9d7bdd1372e015401c247ff836 to your computer and use it in GitHub Desktop.
Simple Network Graph
license: gpl-3.0
height: 500
scrolling: no
border: yes

Simple Network Graph

Basic introductory demo of making a network graph with the d3 force directed simulation.

See my exmple of a swarm plot for a good introduction to generally using the force simulation.

The key ingredient is adding the link force, one of about 5 kinds of forces that D3 provides constructors for.

Physically, the link force behaves like a spring.

It has a length that it wants to have. Shorten it and it pushes outward, lengthen it and it pulls inward.

For each link force, its length and strength are both customisable.

<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- <script type="text/javascript" src='/usr/local/lib/node_modules/d3/build/d3.min.js'></script> -->
</head>
<body>
<script type="text/javascript">
var width = 500,
height = 500
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
var data = {
'nodes': [
{"id": "Meetup", 'color':'black'},
{"id": "Isabell", 'color': 'purple'},
{"id": "Ned", 'color': 'green'},
{"id": "Errol", 'color': 'red'}
],
'links': [
{"source": "Isabell", "target": "Meetup", "value": 0.4},
{"source": "Ned", "target": "Meetup", "value": 0.4},
{"source": "Errol", "target": "Meetup", "value": 0.1}
]
}
var link = svg.selectAll('line')
.data(data.links)
.enter().append('line')
.attr('stroke', 'grey')
.attr('stroke-width', 3)
var node = svg.selectAll('circle')
.data(data.nodes)
.enter().append('circle')
.attr('r', 10)
.attr('fill', function(d){ return d.color})
var simulation = d3.forceSimulation()
.nodes(data.nodes)
.force('link', d3.forceLink(data.links)
.id(function(d) { return d.id; })
.strength(function(d){ return d.value; })
)
.on('tick', tick_function)
.force('center', d3.forceCenter(width / 2, height / 2))
.force('repel_attract', d3.forceManyBody().strength(-100).distanceMin(50))
// .alphaDecay(0)
function tick_function(){
link
.attr('x1', function(d) { return d.source.x; })
.attr('y1', function(d) { return d.source.y; })
.attr('x2', function(d) { return d.target.x; })
.attr('y2', function(d) { return d.target.y; });
node
.attr('cx', function(d) { return d.x; })
.attr('cy', function(d) { return d.y; });
}
console.log(data);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment