Skip to content

Instantly share code, notes, and snippets.

@girliemac girliemac/0.txt
Last active Oct 19, 2017

Embed
What would you like to do?
Snippets for D3 Bubble Chart blog
Demo: http://pubnub.github.io/d3-bubble/
Tutorial: http://www.developer.com/java/fun-with-d3.js-data-visualization-eye-candy-with-streaming-json.html
var diameter = 600;
var svg = d3.select('#chart').append('svg')
.attr('width', diameter)
.attr('height', diameter);
var bubble = d3.layout.pack()
.size([diameter, diameter])
.padding(3); // padding between adjacent circles
.value(function(d) {return d.size;}) // new data will be loaded to bubble layout
var data = {"countries_msg_vol": {
"CA": 170, "US": 393, "CU": 9, "BR": 89, "MX": 192, ..., "Other": 254
}};
function processData(data) {
var obj = data.countries_msg_vol;
var newDataSet = [];
for(var prop in obj) {
newDataSet.push({name: prop, className: prop.toLowerCase(), size: obj[prop]});
}
return {children: newDataSet};
}
.ca, .us {fill: #DF4949;}
.uc, .br, .mx {fill: #E27A3F;}
.other {fill: #45B29D;}
...
var nodes = bubble.nodes(processData(data))
.filter(function(d) { return !d.children; }); // filter out the outer bubble
var vis = svg.selectAll('circle')
.data(nodes, function(d) { return d.name; });
vis.enter().append('circle')
.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; })
.attr('r', function(d) { return d.r; })
.attr('class', function(d) { return d.className; });
<script src="https://cdn.pubnub.com/pubnub-3.x.x.min.js"></script>
var channel = 'rts-xNjiKP4Bg4jgElhhn9v9';
var pubnub = PUBNUB.init({
subscribe_key: 'e19f2bb0-623a-11df-98a1-fbd39d75aa3f'
});
pubnub.subscribe({
channel: channel,
callback: drawBubbles(message)
});
function drawBubbles(message) {
// place the code from the step 1.3
}
var vis = svg.selectAll('circle')
.data(nodes, function(d) { return d.name; });
var duration = 200;
var delay = 0;
// update - This only applies to updating nodes
vis.transition()
.duration(duration)
.delay(function(d, i) {delay = i * 7; return delay;})
.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; })
.attr('r', function(d) { return d.r; })
// enter
vis.enter().append('circle')
.attr('transform', function(d) { return 'translate(' + d.x + ',' + d.y + ')'; })
.attr('r', function(d) { return d.r; })
.attr('class', function(d) { return d.className; })
.style('opacity', 0)
.transition()
.duration(duration * 1.2)
.style('opacity', 1);
// exit
vis.exit()
.transition()
.duration(duration + delay)
.style('opacity', 0)
.remove();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.