【发布时间】:2015-01-08 23:03:27
【问题描述】:
我使用以下示例作为基础,并希望使其成为动态词云 https://github.com/jasondavies/d3-cloud
数据已添加到数组中,但我的词云没有反映新添加的词:
<script>
var fill = d3.scale.category20();
var data = [{word:"Hello",weight:20},{word:"World",weight:10},{word:"Normally",weight:25},{word:"You",weight:15},{word:"Want",weight:30},{word:"More",weight:12},{word:"Words",weight:8},{word:"But",weight:18},{word:"Who",weight:22},{word:"Cares",weight:27}];
d3.layout.cloud().size([500, 500])
.words(data.map(function(d) {
return {text: d.word, size: d.weight};
}))
.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; });
}
function drawUpdate(words){
//alert(JSON.stringify(words)); //shows me the added data
d3.select("body").selectAll("text")
.data(words.map(function(d) {
return {text: d.word, size: d.weight};
}))
.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")
.text(function(d) { return d.text; });
}
setInterval(function () {
var d_new = data;
d_new.push({word: "Mappy",weight:35});
drawUpdate(d_new);
}, 1500);
</script>
此外,它第一次刷新,但没有添加新词。有人可以纠正或指出我在这方面做错了什么。 谢谢
【问题讨论】:
-
您没有在更新函数中处理输入选择(将包含新单词)。
-
但是当我在 data() 之后的 drawUpdate 函数中添加 enter() 时,它给了我 undefined is not a function error in browser console。你能详细说明一下吗
-
代码看起来和你的
draw()函数一样。 -
感谢 Lars,它有点工作,但添加的单词显示在与前一个重叠的相同位置。有什么想法吗?
-
我尝试在更新函数中使用变换属性,但它给出的 d.x 未定义,无法理解这种行为,因为相同的语法适用于绘图函数。为什么在第二个函数中找不到相同数据集的x,y坐标?
标签: json dynamic d3.js word-cloud