Skip to content

Instantly share code, notes, and snippets.

@domadev812
Forked from girliemac/0.txt
Last active November 15, 2017 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save domadev812/551fb8611ac422801df78fca5cadb464 to your computer and use it in GitHub Desktop.
Save domadev812/551fb8611ac422801df78fca5cadb464 to your computer and use it in GitHub Desktop.
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/sdk/javascript/pubnub.4.17.0.js"></script>
var channel = 'rts-xNjiKP4Bg4jgElhhn9v9';
var pubnub = new PubNub({
subscribeKey: 'e19f2bb0-623a-11df-98a1-fbd39d75aa3f',
publishKey: 'myPublishKey',
ssl: true
})
pubnub.subscribe({
channels: ['my_channel'],
});
pubnub.addListener({
message: function (message) {
console.log(message)
}
})
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