d3.js标记来自Json /数组的云大小?

cle*_*ksx 5 json word-cloud d3.js

我正在修改此代码: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>
Run Code Online (Sandbox Code Playgroud)

我想从单独的JSON数据中获取单词和大小数据.我有两个变量

jWord = ["abc","def","ghi,"jkl"];
jCount = ["2", "5", "3", "8"];
Run Code Online (Sandbox Code Playgroud)

jWord有我要在标签云中显示的单词.jCount是相应单词的大小(相同顺序).

我切换到单词jWord,但不知道如何切换大小部分

      .words(jWord.map(function(d) {
        return {text: d, size: 10 + Math.random() * 90};
      }))
Run Code Online (Sandbox Code Playgroud)

我还有另一个Json格式变量.

jWord_Count = ["abc":2, "def":5, "ghi":3, "jkl":8 ];
Run Code Online (Sandbox Code Playgroud)

如果这种格式有帮助.

mbo*_*ock 11

尝试d3.zip:d3.zip(jWord, jCount)返回一个合并数组,其中第一个元素是第一个单词的文本和大小[jWord[0], jCount[0]],第二个元素是第二个单词,依此类推.例如:

.words(d3.zip(jWord, jCount).map(function(d) {
  return {text: d[0], size: d[1]};
}))
Run Code Online (Sandbox Code Playgroud)

实际上,d3.zip将面向列的数据转换为面向行的数据.您也可以以行面向形式表示您的数据,以便开始:

var words = [
  {text: "abc", size: 2},
  {text: "def", size: 5},
  {text: "ghi", size: 3},
  {text: "jkl", size: 8}
];
Run Code Online (Sandbox Code Playgroud)

最后,注意类型.您的计数表示为字符串("2")而不是数字(2).所以你可能想用它+来强迫他们输入数字.