LoginSignup
15
11

More than 5 years have passed since last update.

D3-cloud (d3-v5版) でワードクラウドを作成する

Last updated at Posted at 2018-12-31

ワードクラウドを作成したい。
d3-cloud で作成したという記事をいくつか見つけ、よさそうなので利用することにした。これにあたり、D3の現在のバージョン(v5)にあわせて試行錯誤した。

概要

できあがりイメージ

スクリーンショット 2018-12-31 10.19.50.png

  • ワードと頻度をJSON形式で受け取り、ワードクラウドを作成する
  • クラウドは、
    • ランダムで着色(v5のカラーチャートの範囲で)。
    • ランダムでローテートさせる

実装

GitHub にサンプルがあるので、ご参考ください。

JavaScript

cloud.js
var DATA_FILE_PATH = './data/words.json'; // 読み込みデータファイル
var TARGET_ELEMENT_ID = '#cloud'; // 描画先

d3.json(DATA_FILE_PATH).then(function(data) { // v5
  var h = 490;
  var w = 600;

  var random = d3.randomIrwinHall(2);
  var countMax = d3.max(data, function(d){ return d.count} );
  var sizeScale = d3.scaleLinear().domain([0, countMax]).range([10, 100])

  var words = data.map(function(d) {
    return {
    text: d.word,
    size: sizeScale(d.count) //頻出カウントを文字サイズに反映
    };
  });

  d3.layout.cloud().size([w, h])
    .words(words)
    .rotate(function() { return (~~(Math.random() * 6) - 3) * 30; })
    .font("Impact")
    .fontSize(function(d) { return d.size; })
    .on("end", draw) //描画関数の読み込み
    .start();

  // wordcloud 描画
  function draw(words) {
    d3.select(TARGET_ELEMENT_ID)
      .append("svg")
        .attr("class", "ui fluid image") // style using semantic ui
        .attr("viewBox", "0 0 " + w + " " + h )  // ViewBox : x, y, width, height
        .attr("width", "100%")    // 表示サイズの設定
        .attr("height", "100%")   // 表示サイズの設定
      .append("g")
        .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")")
      .selectAll("text")
        .data(words)
      .enter().append("text")
        .style("font-size", function(d) { return d.size + "px"; })
        .style("font-family", "Impact")
        .style("fill", function(d, i) { return d3.schemeCategory10[i % 10]; })
        .attr("text-anchor", "middle")
        .attr("transform", function(d) {
          return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
        })
        .text(function(d) { return d.text; });
  }

});

d3.json(DATA_FILE_PATH)でJSONファイルを読み込む。
読み込みが完了したら、(1)dataのMapを作り、(2)クラウドのレイアウトを決め、(3)描画する。

HTML

index.html
<!DOCTYPE html>

<html lang="ja">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>d3-cloud(v5)を用いたワードクラウドサンプル</title>
</head>

<body>
  <header></header>
  <DIV id="cloud"></DIV>
  <footer></footer>

  <!-- word cloud -->
  <script src="https://d3js.org/d3.v5.min.js" charset="utf-8"></script>
  <script type="text/javascript" src="js/d3.layout.cloud.js"></script>
  <script src="js/cloud.js"></script>

</body>

</html>

以下の順に読み込んでいる。
- d3ライブラリ(d3.v5.min.js。この例ではCDNで取得。)
- d3-cloudライブラリ(d3.layout.cloud.js。ダウンロード済。)
- 自作したjsファイル(cloud.js)

JSONデータ

words.json
[
    {"word":"イノシシ","count":9},
    {"word":"おにやんま","count":3},
    {"word":"ゆるっと","count":4},
    {"word":"映画","count":3},
                       ・・・
    {"word":"河津桜","count":2}
]

word と count のみ。好きな方法で作ってください。

参考サイト

15
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
11