Last active
April 16, 2022 20:13
-
-
Save RightHandedMonkey/1aa459dee718ce626c15 to your computer and use it in GitHub Desktop.
Full example D3 that shows the lifecycle of charts including: selection, implicit update, enter() and exit()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<button id="heybutton" onclick="clickme()">Update</button> | |
<script id="jsbin-javascript"> | |
//Full example D3 that shows the lifecycle of charts: | |
//Selection: Update, Enter, and Exit | |
var maxSize = 20; | |
var maxLen = 11; | |
var gridSize = 25; | |
var a = getRandData(maxLen); | |
var svg = d3.select("body").append("svg") | |
.attr("width", 300) | |
.attr("height", 150); | |
drawChart(a); | |
function drawChart(data) { | |
var circle = svg.selectAll("circle") | |
.data(data); | |
//The exit selection - these items don't exist in the new dataset so they should be removed | |
//Does not seem to matter where in this sequence the exit() selection is (whether before/after append() or update) | |
circle.exit().transition().duration(1000).attr("r", 0).remove(); | |
//The enter selection - place for handling items not already in the dataset | |
//This part needs to be before the implicit update selection below | |
circle.enter().append("circle") | |
.transition().duration(1000) | |
.attr("r", 2.5); | |
//Implicit update selection - these are items that already exist, but may have new data | |
circle | |
.transition().duration(1000) | |
.attr("cx", function(d, i) { | |
return gridSize * d.index + gridSize; | |
}) | |
.attr("r", function(d) { | |
return (d.size / maxSize) * maxSize; | |
}) | |
.attr("cy", 60); | |
} | |
function removeRandomData(newdata) { | |
var newArr = []; | |
var pctToRemove = 0.25; | |
newdata.forEach(function(d) { | |
if (pctToRemove < Math.random()) { | |
newArr.push(d); | |
} | |
}); | |
return newArr; | |
} | |
function getRandData(num) { | |
var arr = []; | |
for (var i = 0; i < num; i++) { | |
arr.push({ | |
"size": parseInt(Math.random() * maxSize), | |
"index": i | |
}); | |
} | |
return arr; | |
} | |
function clickme() { | |
var newdata = getRandData(maxLen); | |
newdata = removeRandomData(newdata); | |
drawChart(newdata); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment