Skip to content

Instantly share code, notes, and snippets.

@yanhann10
Created April 1, 2018 04:05
Show Gist options
  • Save yanhann10/c556b07b1bd9c4c868c374bd519988fe to your computer and use it in GitHub Desktop.
Save yanhann10/c556b07b1bd9c4c868c374bd519988fe to your computer and use it in GitHub Desktop.
bubble update
license: mit
<html>
<head>
<p>click to update</p>
<style>
body {
margin: 0;
font-family: "Helvetica", sans-serif;
}
text {
text-anchor: middle;
fill: #fff;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/jeezy@1.11.2/lib/jeezy.min.js"></script>
<script>
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var width = window.innerWidth, height = window.innerHeight;
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var pack = d3.pack()
.size([width, height])
.padding(1.5);
var data = [{"name":"campus", "size":10},
{"name":"atlanta", "size":8},
{"name":"havana", "size":6},
{"name":"oh", "size":2},
];
redraw(data);
d3.select("p")
.on("click", function() {
var data1= [{"name":"campus", "size":1},
{"name":"atlanta", "size":1},
{"name":"havana", "size":1},
{"name":"oh", "size":1},
];
redraw(data1);
});
function redraw(classes){
// transition
var t = d3.transition()
.duration(750);
// hierarchy
var h = d3.hierarchy({children: classes})
.sum(function(d) { return d.size; })
//JOIN
var circle = svg.selectAll("circle")
.data(pack(h).leaves(), function(d){ return d.data.name; });
var text = svg.selectAll("text")
.data(pack(h).leaves(), function(d){ return d.data.name; });
//EXIT
circle.exit()
.style("fill", "#b26745")
.transition(t)
.attr("r", 1e-6)
.remove();
text.exit()
.transition(t)
.attr("opacity", 1e-6)
.remove();
//UPDATE
circle
.transition(t)
.style("fill", "#3a403d")
.attr("r", function(d){ return d.r })
.attr("cx", function(d){ return d.x; })
.attr("cy", function(d){ return d.y; })
text
.transition(t)
.attr("x", function(d){ return d.x; })
.attr("y", function(d){ return d.y; });
//ENTER
circle.enter().append("circle")
.attr("r", 1e-6)
.attr("cx", function(d){ return d.x; })
.attr("cy", function(d){ return d.y; })
.style("fill", "#fff")
.transition(t)
.style("fill", "#45b29d")
.attr("r", function(d){ return d.r });
text.enter().append("text")
.attr("opacity", 1e-6)
.attr("x", function(d){ return d.x; })
.attr("y", function(d){ return d.y; })
.text(function(d){ return d.data.name; })
.transition(t)
.attr("opacity", 1);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment