d3.js Tag Cloud size from a Json/array?

2020-07-16 09:17发布

问题:

I am modifying this code: 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

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).

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};
      }))

I also have another Json format variable.

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

If this format helps.

回答1:

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

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}
];

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.