Skip to content

Instantly share code, notes, and snippets.

@lvngd
Created March 10, 2021 19:52
Show Gist options
  • Save lvngd/1d9f56b2c4b8896563c6a6e5651ae795 to your computer and use it in GitHub Desktop.
Save lvngd/1d9f56b2c4b8896563c6a6e5651ae795 to your computer and use it in GitHub Desktop.
Demo of D3 data joins - displaying random subsets from a grid of circles.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<div id="chart"></div>
</body>
<script>
function getRandomInteger(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function drawGraph(){
d3.select("#chart")
.style("width", "400px")
.style("height", "400px");
const enterColor = "#c6db5f",//apple green
updateColor = "#759e7e",//muted green
svgBackgroundColor = '#152c33'
width = 500,
height = 500,
numRows = 12,
numCols = 12,
radius = 16,
numNodes = numRows * numCols;
//x and y axis scales
const y = d3.scaleBand()
.range([0,400])
.domain(d3.range(numRows));
const x = d3.scaleBand()
.range([0, 400])
.domain(d3.range(numCols));
let circleNodes = d3.range(numNodes).map(function(i) {
return {
id: i,
radius: radius,
x: x(i%numCols),
y: y(Math.floor(i/numCols))
};
});
const svg = d3.select('#chart')
.append('div')
.classed('svg-container', true)
.append('svg')
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 500 500")
.classed('svg-content-responsive', true)
.style("background-color", svgBackgroundColor)
.append('g');
//container to hold the grid
const container = svg.append("g")
.attr("transform", `translate(65,65)`);
function update(nodes){
let t = d3.transition()
.duration(750);
let circles = container.selectAll("circle")
.data(nodes,d=>d.id);
circles
.join(
enter => enter.append("circle")
.attr("fill", enterColor),
update => update
.attr("fill", updateColor),
exit => exit
.style("opacity", 0.4)
.call(e => e.transition(t).remove())
)
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.attr('r', d => d.radius)
}
//initial layout
update(circleNodes);
d3.interval(function() {
update(d3.shuffle(circleNodes)
.slice(0, getRandomInteger(5,circleNodes.length)));
}, 2500);
}
//call function to draw the graph
drawGraph();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment