【问题标题】:d3.js Tag Cloud size from a Json/array?d3.js 来自 Json/array 的标记云大小?
【发布时间】:2014-06-17 19:13:33
【问题描述】:

我正在修改这段代码: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 数据中获取单词和大小数据。 我有两个变量

jWord = ["abc","def","ghi,"jkl"];
jCount = ["2", "5", "3", "8"];

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

我把word切换到jWord,但是不知道怎么在里面切换大小部分

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

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

jWord_Count = ["abc":2, "def":5, "ghi":3, "jkl":8 ];

如果这种格式有帮助的话。

【问题讨论】:

    标签: json d3.js word-cloud


    【解决方案1】:

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

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

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

    var words = [
      {text: "abc", size: 2},
      {text: "def", size: 5},
      {text: "ghi", size: 3},
      {text: "jkl", size: 8}
    ];
    

    最后,注意类型。您的计数表示为字符串 ("2") 而不是数字 (2)。因此,您可能想使用+ 将它们强制转换为数字。

    【讨论】:

    • 如果要声明一个JSON var,即var topicsJson = [ {'abc': 2 },{'def': 5},{'ghi': 3},{'jkl': 8}];,在return语句中如何处理?
    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多