Skip to content

Instantly share code, notes, and snippets.

@jerng
Last active April 3, 2020 01:13
Show Gist options
  • Save jerng/b47cf70fc0fd20ccf56cdb42e172e877 to your computer and use it in GitHub Desktop.
Save jerng/b47cf70fc0fd20ccf56cdb42e172e877 to your computer and use it in GitHub Desktop.
d3.v5 - forceSimulation - Adding New [data+element]s - Minimal Example
license: gpl-3.0
height: 800
scrolling: no
border: yes
<!DOCTYPE html>
<svg/>
<h1><code>d3.js</code>, Version 5.x, Force Layout primer</h1>
<h2>For study purposes only</h2>
<ul>
<li><h6>Sought to clean up an example from :</h6>
https://bl.ocks.org/mbostock/1095795/8f34afdd6d321b71ca6b3a5904e486f3173f1111 Original example license : https://opensource.org/licenses/GPL-3.0
<ul>
<li><h6>Fix option 1: subsequently assisted by Mihael Ankerst:</h6>
https://bl.ocks.org/EE2dev/e653b5c781b642c164bd4710031243ca Assisted solution license : https://opensource.org/licenses/MIT</li>
<li><h6>Fix option 2: subsequently assisted by Brian Wong:</h6>
https://bl.ocks.org/brianwfl88/459b2ef7344e8d63239365b62aa454a9 Assisted solution license : https://opensource.org/licenses/GPL-3.0</li>
</ul>
</li>
<li><h6>Cleaned up example uses d3 version 5.</h6></li>
<li><h6>Original example uses d3 version 4.</h6></li>
</ul>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="../../../third-party/live.js"></script>
<script>
'use strict'
let p = thing => JSON.stringify ( thing, null, 2 )
let width = 500,
height = 500,
color = d3.scaleOrdinal(d3.schemeCategory10),
svg = d3.select ( 'svg' )
.attr ( 'width', width )
.attr ( 'height', height )
.attr ( 'style', 'background-color:#eeeeee' )
let a = { id: 'a' },
b = { id: 'b' },
c = { id: 'c' },
dataArray = [ a, b, c ]
let g = svg.append ( 'g' )
.attr ( 'transform',
'translate( ' + width / 2 + ',' + height / 2 + ' )' ),
gg = g.append ( 'g' )
.attr ( 'stroke', '#fff' )
.attr ( 'stroke-width', 1.5)
.selectAll () // empty selection
let restart = function restart () {
gg = gg
.data ( dataArray, d => d.id )
.join (
enterer => enterer
.append ( 'circle' )
.attr("fill", d => color(d.id) )
.attr("r", 8)
)
// Fix Option 1: "add these two lines here" - Mihael Ankerst
simulation.nodes ( dataArray )
//simulation.restart ()
},
tickHandler = function () {
gg .attr( 'cx', d => d.x )
.attr( 'cy', d => d.y )
}
let simulation = d3.forceSimulation ( dataArray )
.force ( 'charge', d3.forceManyBody ().strength ( -1000 ) )
.force ( 'x', d3.forceX () )
.force ( 'y', d3.forceY () )
.alphaTarget ( 1 )
.on ( 'tick', tickHandler )
restart()
setTimeout ( () => {
dataArray.pop()
restart()
}, 1000 )
setTimeout ( () => {
dataArray.push(c)
restart()
}, 2000 )
setTimeout ( () => {
dataArray.push( { id: 'd' } )
// Fix Option 2: an alternative to Fix Option 1
// simulation.nodes ( dataArray )
restart()
}, 3000 )
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment