I'm trying out this example of an animated word cloud, using jasondavies's d3.layout.cloud.
It works with d3 version 3, but if you update it with any version above it won't display correctly. You can still see the transition of some words but the others remain in the middle with no scaling.
I'm putting the code here as reference.
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<!--script src="http://d3js.org/d3.v3.min.js"></script-->
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://rawgit.com/jasondavies/d3-cloud/master/build/d3.layout.cloud.js"></script>
<script>
//Simple animated example of d3-cloud - https://github.com/jasondavies/d3-cloud
//Based on https://github.com/jasondavies/d3-cloud/blob/master/examples/simple.html
// Encapsulate the word cloud functionality
function wordCloud(selector) {
//var fill = d3.scale.category20();
//Construct the word cloud's SVG element
var svg = d3.select(selector).append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform", "translate(250,250)");
//Draw the word cloud
function draw(words) {
var cloud = svg.selectAll("g text")
.data(words, function(d) { return d.text; })
//Entering words
cloud.enter()
.append("text")
.style("font-family", "Impact")
.style("fill", "black")
.attr("text-anchor", "middle")
.attr('font-size', 1)
.text(function(d) { return d.text; });
//Entering and existing words
cloud
.transition()
.duration(600)
.style("font-size", function(d) { return d.size + "px"; })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("fill-opacity", 1);
//Exiting words
cloud.exit()
.transition()
.duration(200)
.style('fill-opacity', 1e-6)
.attr('font-size', 1)
.remove();
}
//Use the module pattern to encapsulate the visualisation code. We'll
// expose only the parts that need to be public.
return {
//Recompute the word cloud for a new set of words. This method will
// asycnhronously call draw when the layout has been computed.
//The outside world will need to call this function, so make it part
// of the wordCloud return value.
update: function(words) {
d3.layout.cloud().size([500, 500])
.words(words)
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
}
}
}
//Some sample data - http://en.wikiquote.org/wiki/Opening_lines
var words = [
"You don't know about me without you have read a book called The Adventures of Tom Sawyer but that ain't no matter.",
"The boy with fair hair lowered himself down the last few feet of rock and began to pick his way toward the lagoon.",
"When Mr. Bilbo Baggins of Bag End announced that he would shortly be celebrating his eleventy-first birthday with a party of special magnificence, there was much talk and excitement in Hobbiton.",
"It was inevitable: the scent of bitter almonds always reminded him of the fate of unrequited love."
]
//Prepare one of the sample sentences by removing punctuation,
// creating an array of words and computing a random size attribute.
function getWords(i) {
return words[i]
.replace(/[!\.,:;\?]/g, '')
.split(' ')
.map(function(d) {
return {text: d, size: 10 + Math.random() * 60};
})
}
//This method tells the word cloud to redraw with a new set of words.
//In reality the new words would probably come from a server request,
// user input or some other source.
function showNewWords(vis, i) {
i = i || 0;
vis.update(getWords(i ++ % words.length))
setTimeout(function() { showNewWords(vis, i + 1)}, 2000)
}
//Create a new instance of the word cloud visualisation.
var myWordCloud = wordCloud('body');
//Start cycling through the demo data
showNewWords(myWordCloud);
</script>
Note: I edited the fill color from the example to be black. If you want to use the original color palette in d3 v4 or above, you need to use var fill = d3.scaleOrdinal(d3.schemeCategory10)
Ok so I did some digging, they basically merged the enter and update function into one using merge starting from version v4.
So for the above to work, you have to replace
//Entering words
cloud.enter()
.append("text")
.style("font-family", "Impact")
.style("fill", "black")
.attr("text-anchor", "middle")
.attr('font-size', 1)
.text(function(d) { return d.text; });
//Entering and existing words
cloud
.transition()
.duration(600)
.style("font-size", function(d) { return d.size + "px"; })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("fill-opacity", 1);
with
//Entering words
cloud.enter()
.append("text")
.style("font-family", "Impact")
.style("fill", "black")
.attr("text-anchor", "middle")
.attr('font-size', 1)
.text(function(d) { return d.text; })
//Entering and existing
.merge(cloud).transition()
.duration(600)
.style("font-size", function(d) { return d.size + "px"; })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.style("fill-opacity", 1);
Related
I am using Jason Davies's sample word cloud generator code to create a word cloud. I am able to draw it but the shape of the word cloud I would like is oval/circular. I am aware that there have been questions regarding the circular shape of Jason Davies's word cloud but they all were talking about making changes in the build code function place() and were also unanswered. I am wondering if there is a way to achieve the oval/circular shape modifying the following code:
var fill = d3.scale.category20();
var layout = cloud()
.size([500, 500])
.words([
"Hello", "world", "normally", "you", "want", "more", "words",
"than", "this"].map(function(d) {
return {text: d, size: 10 + Math.random() * 90, test: "haha"};
}))
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw);
layout.start();
function draw(words) {
d3.select("body").append("svg")
.attr("width", layout.size()[0])
.attr("height", layout.size()[1])
.append("g")
.attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
In the readme of Jason Davies's Github, there is a mention of spiralfor word positioning and I am unable to understand since I am very new to the JavaScript. Does anyone has any suggestions? Thanks a lot.
Add the following: .spiral("archimedean")
I just got the word cloud template from T3. Now I added a youtube link to every word in the word cloud, but I want the video pop up while I clicked the words in the word cloud. How should I modify my code? Thanks a lot.
Here is my Javascript:
<script>
var fill = d3.scale.category20();
var words = [{"text":"Worry", "url":"http://google.com/"},
{"text":"Choices", "url":"http://bing.com/"},
]
var width = 1080;
var height = 500;
for (var i = 0; i < words.length; i++) {
words[i].size = 10 + Math.random() * 90;
}
d3.layout.cloud()
.size([width, height])
.words(words)
.padding(5)
.rotate(function() { return ~~ ((Math.random() * 6) - 3) * 30 + 8; })
.font("Impact")
.fontSize(function(d) { return d.size;})
.on("end", draw)
.start();
function draw(words) {
d3.select("#word-cloud")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate("+ width/2 +","+ height/2 +")")
.selectAll("text")
.data(words)
.enter()
.append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; })
.on("click", function (d, i){
window.open(d.url, "_blank");
});
}
My proposed approach:
Create a modal window
Open the modal when a word is clicked
Dynamically populate the embed code into the modal based on which word is clicked (I didn't do this part for you, but should be easily doable as it's part of the data to access).
I created a JSFiddle that gets you most of the way, with additional work needed here:
.on("click", function (d, i){
// Dynamically populate embed
// Open the modal
document.getElementById('myModal').style.display = "block";
});
I adapted Ger Hobbelt's excellent example of group/bundle nodes
https://gist.github.com/GerHobbelt/3071239
as a JSFiddle here:
https://jsfiddle.net/NovasTaylor/tco2fkad/
The display demonstrates both collapsible nodes and regions (hulls).
The one tweak that eludes me is how to add labels to expanded nodes. I have successfully added labels to nodes in my other force network diagrams using code similar to:
nodes.append("text")
.attr("class", "nodetext")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) {
// d.name is a label for the node, present in the JSON source
return d.name;
});
Is anyone familiar enough with Ger's example to guide me in the right direction?
On enter, instead of appending circle append a g with a circle and a text. Then re-factor a bit to fix the movement of the g instead of the circle. Finally, append write out the .text() only if the node has a name (meaning it's a leaf):
node = nodeg.selectAll("g.node").data(net.nodes, nodeid);
node.exit().remove();
var onEnter = node.enter();
var g = onEnter
.append("g")
.attr("class", function(d) { return "node" + (d.size?"":" leaf"); })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
g.append("circle")
// if (d.size) -- d.size > 0 when d is a group node.
.attr("r", function(d) { return d.size ? d.size + dr : dr+1; })
.style("fill", function(d) { return fill(d.group); })
.on("click", function(d) {
expand[d.group] = !expand[d.group];
init();
});
g.append("text")
.attr("fill","black")
.text(function(d,i){
if (d['name']){
return d['name'];
}
});
And refactored tick to use g instead of circle:
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
Updated fiddle.
I'm afraid this is a very basic Javascript question on building an array from HTML elements. I've had a search for answers, but I think there's important fundamentals that aren't clicking for me and I'm going in circles, so some outside, expert perspective would be appreciated!
We're using Moodle to run an online course, and in the introduction week, we want to collect some information on users with a database module, such as country, and then show them the group responses.
Moodle give a template with a placeholder [[data]], which you can wrap in html, in this case a div:
<div class="country">[[country]]</div>
The issue I'm having is getting the content of all these divs into an array. I found this method explained here, but my attempts to push/concat didn't seem to work:
var countryList = document.getElementsByClassName("country");
Array.prototype.forEach.call(countryList, function() {});
The reason I want it in an array is so I can push the content into an existing template using Jason Davies's d3.js powered word cloud. Here's a link to GitHub, and the very basic code for a simple cloud is copied below for reference.
Essentially I want to be able to make an array from HTML elements and combine it with the words array used below:
var fill = d3.scale.category20();
d3.layout.cloud().size([300, 300])
.words([
"Hello", "world", "normally", "you", "want", "more", "words",
"than", "this"
].map(function(d) {
return {
text: d,
size: 10 + Math.random() * 90
};
}))
.padding(5)
.rotate(function() {
return ~~(Math.random() * 2) * 90;
})
.font("Impact")
.fontSize(function(d) {
return d.size;
})
.on("end", draw)
.start();
function draw(words) {
d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) {
return d.size + "px";
})
.style("font-family", "Impact")
.style("fill", function(d, i) {
return fill(i);
})
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) {
return d.text;
});
}
You should be able to get the array you want using something like:
var countryList = document.querySelectorAll('.country');
var countryNames = Array.prototype.map.call(countryList, function(c){return c.textContent});
I am using the word cloud library in D3 by Jason Davies. This is the normal code which I am using and works fine for creating the word clouds.
d3.layout.cloud().size([width, height])
.words(d3.zip(vis_words, vis_freq).map(function(d) {
return {text: d[0], size: wordScale(d[1]) };
}))
.padding(1)
.rotate(function() { return ~~(Math.random() * 2) * 0; })
.font("times")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function draw(words) {
d3.select(curr_id).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")")
.selectAll("text")
.data(words)
.enter()
.append("text")
.transition()
.delay(function(d,i){
return i*100;
})
.duration(1000)
.ease("elastic")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "times")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
I have a time slider to select a specific value, based on which words in the word cloud have different frequency(given by size) or some of the words are not there at all. I need to update without redrawing the entire word cloud which I am currently doing. In a way, I want to keep the position of words fixed and just updating their size and whether they exist based on the value selected on a slider?
Should I enter an update function in the function draw for this? Am certainly new to D3 and any help would be great?
To do this, you would select the existing text elements and set the font-size property for them. The code to do this looks like this:
d3.select("svg").selectAll("text")
.style("font-size", function(d, i) { // do something });