Public
Edited
Oct 16, 2023
Insert cell
Insert cell
Insert cell
viewof chart = {
// Specify the dimensions of the chart.
const width = 928;
const height = 800;

// Specify the color scale.
const color = d3.scaleOrdinal(d3.schemeCategory10);

let selectedNode = null;
const nodeStroke = '#fff';
const nodeStrokeWidth = 1.5;
const nodeStrokeOpacity = 1;
const linkOpacity = 0.6;
const nodeDeselectOpacity = 0.4;
const linkDeselectOpacity = 0.2;
const nodeHightlightStroke = '#ffd700';
const nodeHightlightStrokeWidth = 2.0;

// The force simulation mutates links and nodes, so create a copy
// so that re-evaluating this cell produces the same result.
const links = data.links.map(d => ({...d}));
const nodes = data.nodes.map(d => ({...d}));

const nodeDistanceMax = 270;
const nodeStrength = -50;
const linkDistance = 50;
const forceNode = d3.forceManyBody();
const forceLink = d3.forceLink(links).id(d => d.id);
forceNode.strength(nodeStrength);
forceNode.distanceMax(nodeDistanceMax);
forceLink.distance(linkDistance);

// Create a simulation with several forces.
const simulation = d3.forceSimulation(nodes)
.force("link", forceLink)
.force("charge", forceNode)
.force("center", d3.forceCenter(width / 2, height / 2))
.on("tick", ticked);

// Create the SVG container.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto;");

svg.on('click', deselect_node);

// Add a line for each link, and a circle for each node.
const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", linkOpacity)
.selectAll()
.data(links)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.value));

const scale = d3.scaleSqrt()
.domain(d3.extent(nodes, n => n.playcount))
.range([2, 20])
const node = svg.append("g")
.attr("stroke", nodeStroke)
.attr("stroke-width", nodeStrokeWidth)
.selectAll()
.data(nodes)
.join("circle")
.attr("r", d => scale(d.playcount))
.attr("fill", d => color(d.artist))
.on('click', clicked);

node.append("title")
.text(d => d.artist + ": " + d.name);

// Add a drag behavior.
node.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
// Set the position attributes of links and nodes each time the simulation ticks.
function ticked() {
link
.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("cx", d => d.x)
.attr("cy", d => d.y);
}

// Reheat the simulation when drag starts, and fix the subject position.
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}

// Update the subject (dragged node) position during drag.
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}

// Restore the target alpha so the simulation cools after dragging ends.
// Unfix the subject position now that it’s no longer being dragged.
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}

function clicked(event, d) {
event.stopPropagation();
const allNodes = svg.selectAll('circle')
.attr('stroke', nodeStroke)
.attr('stroke-width', nodeStrokeWidth)
.attr('stroke-opacity', nodeDeselectOpacity)
.attr('fill-opacity', nodeDeselectOpacity);

const allLinks = svg.selectAll('line')
.attr('stroke-opacity', linkDeselectOpacity);

const currentNode = d3.select(this)
.attr('stroke', nodeHightlightStroke)
.attr('stroke-width', nodeHightlightStrokeWidth)
.attr('stroke-opacity', nodeStrokeOpacity)
.attr('fill-opacity', nodeStrokeOpacity);

selectedNode = d;
svg.property('value', Object.assign(svg.node(),
{ selectedNode: d })).dispatch('input');
}

function deselect_node(event) {
const allNodes = svg.selectAll('circle')
.attr('stroke', nodeStroke)
.attr('stroke-width', nodeStrokeWidth)
.attr('stroke-opacity', nodeStrokeOpacity)
.attr('fill-opacity', nodeStrokeOpacity);

const allLinks = svg.selectAll('line')
.attr('stroke-opacity', linkOpacity);

selectedNode = null;
svg.property('value', Object.assign(svg.node(),
{ selectedNode: null })).dispatch('input');
}

// When this cell is re-run, stop the previous simulation. (This doesn’t
// really matter since the target alpha is zero and the simulation will
// stop naturally, but it’s a good practice.)
invalidation.then(() => simulation.stop());

return Object.assign(svg.node(), { selectedNode: null });
}
Insert cell
Insert cell
Insert cell
data = d3.json("https://gist.githubusercontent.com/emanueles/7b7723386677bb13763208216fd89c1f/raw/d09478158ba0fe8aa616deee8bcfe908bba17f15/songs.json")
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