d3.js从Json /数组标记云的大小? [英] d3.js Tag Cloud size from a Json/array?
问题描述
我要修改此代码: https://github.com/jasondavies/d3-cloud
<script>
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};
}))
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.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"; })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
</script>
我想从单独的JSON数据获取单词和大小数据。
我有两个变量
I'd like to get the word and size data from separate JSON data. I have two variables
jWord = ["abc","def","ghi,"jkl"];
jCount = ["2", "5", "3", "8"];
$ b b
jWord有我要在标签云中显示的字词
jCount是相应字词的大小(相同的顺序)。
jWord has the words that I want to display in the tag clouds. jCount is the size of the corresponding word (same order).
我切换到jWord的字,但不知道如何在
I switched to the word to jWord, but not sure how to switch the size part in
.words(jWord.map(function(d) {
return {text: d, size: 10 + Math.random() * 90};
}))
我还有另一个Json格式的变量。
I also have another Json format variable.
jWord_Count = ["abc":2, "def":5, "ghi":3, "jkl":8 ];
如果此格式有帮助。
推荐答案
请尝试 d3.zip : d3.zip(jWord,jCount)
返回一个合并数组,其中第一个元素是文本,第一个单词的大小 [jWord [0],jCount [0]]
,第二个单元是第二个单词,以此类推。例如:
Try d3.zip: d3.zip(jWord, jCount)
returns a merged array where the first element is the text and size of the first word [jWord[0], jCount[0]]
, the second element is the second word, and so on. For example:
.words(d3.zip(jWord, jCount).map(function(d) {
return {text: d[0], size: d[1]};
}))
实际上,d3.zip将面向列的数据转换为面向行的数据。您也可以以行为方式表示您的数据,开头为:
In effect, d3.zip turns column-oriented data into row-oriented data. You could also just represent your data in row-oriented form to begin with:
var words = [
{text: "abc", size: 2},
{text: "def", size: 5},
{text: "ghi", size: 3},
{text: "jkl", size: 8}
];
最后,注意类型。您的计数表示为字符串(2
)而不是数字( 2
)。因此,您可能想使用 +
强制他们加入数字。
Lastly, watch out with types. Your counts are represented as strings ("2"
) rather than numbers (2
). So you might want to use +
to coerce them to numbers.
这篇关于d3.js从Json /数组标记云的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!