Skip to content

Instantly share code, notes, and snippets.

@VictorDu
Created March 7, 2016 01:00
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 VictorDu/9558a11de4f12f3e8bad to your computer and use it in GitHub Desktop.
Save VictorDu/9558a11de4f12f3e8bad to your computer and use it in GitHub Desktop.
USF_VictorDu_Bubble_chart
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: 10px sans-serif;
}
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<script>
var diameter = 960,
format = d3.format(",d"),
color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(1.5);
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function(d) {
return "<strong>State:</strong> <span style='color:red'>" + d.state + "</span></br>" +
"<strong>Population:</strong> <span style='color:red'>" + d.value + "</span>";
})
var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
svg.call(tip);
d3.csv("https://gist.githubusercontent.com/VictorDu/fbd642275a936c99c90c/raw/412276f252fa93b23cd5c6d2f68e8fbb66fe2112/States.csv", function(error, data) {
if (error) throw error;
data.forEach(function(d) {
d.pop = +d.pop;
d.state = d.state;
});
console.log(bubble.nodes(classes(data)));
var node = svg.selectAll(".node")
.data(bubble.nodes(classes(data)).filter(function(d) { return !d.children; }))
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.on('mouseover', tip.show)
.on('mouseout', tip.hide);
node.append("title")
.text(function(d) { return d.className + ": " + format(d.value); });
node.append("circle")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { console.log(d.state); return color(d.state); });
node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d) { return d.state });
});
// Returns a flattened hierarchy containing all leaf nodes under the root.
function classes(data) {
var classes = [];
data.forEach(function(d){
classes.push({value: d.pop, state: d.state})
})
return {children: classes};
}
d3.select(self.frameElement).style("height", diameter + "px");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment