Skip to content

Instantly share code, notes, and snippets.

@girliemac
Last active July 22, 2016 21:03
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 girliemac/090036e6729200b7fdc0 to your computer and use it in GitHub Desktop.
Save girliemac/090036e6729200b7fdc0 to your computer and use it in GitHub Desktop.
Snippets for D3 Word Cloud blog
<script src="https://cdn.pubnub.com/pubnub-3.15.2.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="js/d3.layout.cloud.js"></script>
function calculateCloud(data) {
d3.layout.cloud()
.size([600, 400])
.words(data) // data from PubNub
.rotate(function() { return ~~(Math.random()*2) * 90;}) // 0 or 90deg
.fontSize(function(d) { return d.size; })
.on('end', drawCloud)
.start();
}
function drawCloud(words) {
d3.select('#cloud').append('svg')
.attr('width', 600).attr('height', 400)
.append('g')
.selectAll('text')
.data(words)
.enter().append('text')
.style('font-size', function(d) { return d.size + 'px'; })
.style('font-family', function(d) { return d.font; })
.style('fill', function(d, i) { return colors(i); })
.attr('text-anchor', 'middle')
.attr('transform', function(d) {
return 'translate(' + [d.x, d.y] + ')rotate(' + d.rotate + ')';
})
.text(function(d) { return d.text; });
}
pubnub.history({
channel: 'chat',
count: 100,
callback: function(m) {
calculateCloud(processData(m[0]));
}
});
function processData(messages) {
// Strip off punctuations from strings in ['message1', 'message2',...]
// Count frequency of words
// Returns in key/value form for d3.layout.cloud
// See https://github.com/pubnub/d3-wordcloud for the entire code
return wordCountArr // [{text: 'str', size: n},...]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment