質問

このコードを変更しています: 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 データから取得したいと考えています。変数が 2 つあります

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

この形式がお役に立てれば。

役に立ちましたか?

解決

試す d3.zip: d3.zip(jWord, jCount) 最初の要素が最初の単語のテキストとサイズである結合された配列を返します。 [jWord[0], jCount[0]], 、2 番目の要素は 2 番目の単語、などとなります。例えば:

.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)。したがって、使用したいかもしれません + 彼らに数字を強制するために。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top