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

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

我切换到绑定到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 ];
.

如果此格式有帮助。

有帮助吗?

解决方案

try d3.zip d3.zip(jWord, jCount)返回一个合并的阵列,其中第一个元素是文本和第一个单词生成的大小,第二个元素是第二个词,等等。例如:

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

最后,用类型观看。您的计数表示为字符串([jWord[0], jCount[0]])而不是数字("2")。因此,您可能希望使用2将它们推移到数字。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top