阅读背景:

d3.js来自Json /数组的Tag Cloud大小?

来源:互联网 

I am modifying this code: https://github.com/jasondavies/d3-cloud

我正在修改此代码: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>

I'd like to get the word and size data from separate JSON data. I have two variables

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

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

jWord has the words that I want to display in the tag clouds. jCount is the size of the corresponding word (same order).

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

I switched to the word to jWord, but not sure how to switch the size part in

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

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

I also have another Json format variable.

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

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

If this format helps.

如果这种格式有帮助。

1 个解决方案

#1


11  

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:

尝试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]};
}))

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:

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

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

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.

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


分享到: