I created this to help me understand object constancy and how to add and remove data. The following two tutorials helped me greatly.
http://www.samselikoff.com/writings/intro-to-d3/
https://medium.com/@c_behrens/enter-update-exit-6cafc6014c36#.4ctg82y0y
xxxxxxxxxx
<html>
<head>
<!-- from https://www.samselikoff.com/writings/intro-to-d3/ -->
<!-- from https://medium.com/@c_behrens/enter-update-exit-6cafc6014c36#.4ctg82y0y -->
<meta charset='utf-8'>
<title>Object Constancy in D3 Tutorial</title>
<style>
</style>
</head>
<body>
<button id="add-btn">Add Element</button>
<button id="remove-btn">Remove Element</button>
<script type="text/javascript" src="https://d3js.org/d3.v3.min.js"></script>
<script>
// initial number of rectangles to display
var numRects = 4;
// set up the svg container
var svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 200);
// get the data
d3.csv("data.csv", function(data) {
// store the data in a variable
origionalData = data;
// call the init function and pass the number of rectangles
init(numRects);
});
function init(numRects) {
// get only the data for the number of rectangles
myData4 = origionalData.slice(0, numRects);
// call the update function and pass the data for the
// number of rectangles
update(myData4);
}
function update(data) {
// bind the data to the rectangles and specify a key function
var bars = svg.selectAll("rect")
.data(data, function(d, i) {
return d.name;
});
// display the rectangles
bars.enter()
.append('rect')
.attr('width', 20)
.attr('height', function(d, i) {
return d.value
})
.attr("x", function(d, i) {
return i * 30;
})
.attr('y', function(d, i) {
return 200 - d.value;
})
.on("click", function(e, i) {
//console.log(this);
//this.remove();
});
// remove the last rectangle when data is changed.
// when the data is different from before this will remove
// the rectangles where the data is no longer in the array
bars.exit().remove();
}
// increment the number of rectangles and call the init array
d3.select("#add-btn").on("click", function(e) {
init(++numRects);
});
// decrement the number of rectangles and call the init array
d3.select("#remove-btn").on("click", function(e) {
init(--numRects);
});
</script>
</body>
</html>
https://d3js.org/d3.v3.min.js