Skip to content

Instantly share code, notes, and snippets.

@chule
Last active September 11, 2019 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chule/988c8382f48674bb020c7b3d326f086b to your computer and use it in GitHub Desktop.
Save chule/988c8382f48674bb020c7b3d326f086b to your computer and use it in GitHub Desktop.
circles selection.join
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var margin = {top: 50, right: 40, bottom: 50, left: 40};
var svgWidth = 960,
svgHeight = 500;
var width = svgWidth - (margin.left + margin.right);
var height = svgHeight - (margin.top + margin.bottom);
var svg = d3.select("body").append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight)
var button = svg
.append("g")
.attr("transform", "translate(20,20)")
button
.append("rect")
.attr("width", 110)
.attr("height", 50)
.attr("class", "button")
.style("fill", "darkred");
button
.append("text")
.text("CLICK ME")
.attr("x", 10)
.attr("y", 32)
.style("fill", "white")
.style("pointer-events", "none")
.attr("font-family", "monospace")
.attr("font-size", 18)
var dataset0 = true;
button.on("click", function() {
if (dataset0) {
d3.select(".button")
.style("fill", "steelblue")
draw(data1);
dataset0 = false;
} else {
d3.select(".button")
.style("fill", "darkred")
draw(data0);
dataset0 = true;
}
});
var data0 = [10,20,50,30,40,33,78];
var data1 = [40,20,80,30,55,22,22,66];
var extent = d3.extent(data0.concat(data1), function (d) {return d});
var xScale = d3.scaleLinear()
.domain(extent)
.range([0, width]);
var mainG = svg.append("g")
.attr("transform","translate(" + [margin.left, margin.top] + ")");
function draw(data) {
var circles = mainG.selectAll("circle")
.data(data)
.join(
enter => enter.append("circle")
.attr("cy", 200)
.attr("r", function(d,i) {return d})
.style("fill", "green")
.attr("cx", d => xScale(d)),
update => update
.style("fill", "steelblue")
.transition()
.duration(750)
.attr("cx", d => xScale(d)),
exit => exit
.style("fill", "darkred")
.transition()
.duration(750)
.style("opacity", 0)
.remove()
);
};
draw(data0);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment