Published
Edited
Oct 25, 2019
Insert cell
Insert cell
chart = {

function zoom_actions(){
group.attr("transform", d3.event.transform)
}
const links = data.links.map(d => Object.create(d));
const nodes = data.nodes.map(d => Object.create(d));

const forceCollide = d3.forceCollide(d => d.influence * d.character.length)
.strength(0.8);
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id).distance(100))
.force("charge", d3.forceManyBody())
.force('collide', forceCollide)
.force("center", d3.forceCenter(width / 2, height / 2));

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style('border', '5px dashed rgba(0,0,0,0.5)');

const group = svg.append('g');
const link = group
.selectAll("line")
.data(links)
.join("line")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.attr("stroke-width", d => Math.sqrt(d.value));

const node = group.selectAll(".node")
.data(nodes)
.enter()
.append('g')
.attr('class', 'node')
.call(drag(simulation));
//Add labels to each node
const label = node.append("text")
.attr("dx", 12)
.attr("dy", "0.35em")
.attr("font-size", function(d){ return d.influence*1.5>9? d.influence*1.5: 9; })
.text(function(d){ return d.character; });
//Add circles to each node
const circle = node.append("circle")
.attr("r", function(d){ return d.influence/2>5 ? d.influence/2 : 5; })
.attr("fill", function(d){ return color(d); });


simulation.on("tick", () => {
link
.attr("stroke-width", d => d.weight / 10)
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);

node
.attr('r', d => d.influence)
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});

invalidation.then(() => simulation.stop());

return svg.node();
}
Insert cell
data = d3.json("https://gist.githubusercontent.com/virtuaCode/694e8dbaccf8e69620aac837de15cb21/raw/edde90c47729af260bbc2bbda058ea72e4325282/got.json")
Insert cell
height = 600
Insert cell
color = {
const scale = d3.scaleOrdinal(d3.schemeCategory10);
return d => scale(d.zone);
}
Insert cell
drag = simulation => {
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;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
d3 = require("d3@5")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more