I didn\'t explain the issue properly in the title... Sorry.
I\'m following the D3 Tag Cloud Simple example https://github.com/jasondavies/d3-cloud/blob/master/exampl
I suggest you should use the built-in import function for json instead of php. I think that the problem you have is that the reading of the data is asynchronous, so words
is not filled before using it in clouds.
The principle behind d3.json()
is to do everything in this function, which will be executed when the json is loaded:
var data; // a global
d3.json("path/to/file.json", function(error, json) {
if (error) return console.warn(error);
data = json;
visualizeit();
});
EDIT
Here is an example of the code that should work, I just added the d3 cloud example inside the json function.
d3.json("../../../assets/json/tweetTags.json", function(error, json) {
if (error) return console.warn(error);
var fill = d3.scale.category20();
d3.layout.cloud().size([300, 300])
.words([ // To be replaced with data
"Hello", "world", "normally", "you", "want", "more", "words",
"than", "this"].map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
.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; });
}
})
Then, when this version works you can just replace the .words()
by:
.words(json.map(function(d) {
return {text: d.word, size: d.sentiment * 40, tweet: d.tweet};
}))
Can you extract other entries of your data? e.g. words and sentiment?
Maybe you could try it like following code. If it works, you can change it to your codes.
var data; // a global
d3.json("path/to/file.json", function(error, json) {
if (error) return console.warn(error);
d3.select("#vis").append("svg")
.data(json)
.enter().append("text")
.text(function(d) {return d.tweets;});
});
I had the exact same problem with the words going out of the svg container and i solved it by inserting a variable called origin that i put to (width/2) in the translate method. The border problems were caused by the fact that the alghorithm is made to keep them inside as long as you use the correct center ot the projection field for example: width=300, height=300 that means origin=150. I hope that helps you.