Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
18
Help us understand the problem. What is going on with this article?
@daikumatan

Scott Murray D3.js チュートリアルまとめ

More than 5 years have passed since last update.

センサデータをリアルタイム可視化したいと思い、D3.jsのお勉強をはじめました。
そこで、スコットマレイさんのDS.jsのチュートリアル!!とてもわかりやすいです.

とはいえ、完全なソースが記述されているわけでなく、全体の見通しが悪いかなぁーと思い、各セクションの終了時のソースコードを記載しました。


01. このチュートリアルについて

省略.詳細は下記
http://ja.d3js.info/alignedleft/tutorials/d3/about/

02. 基礎編

省略.詳細は下記
http://ja.d3js.info/alignedleft/tutorials/d3/fundamentals/

03. セットアップ

省略.詳細は下記
http://ja.d3js.info/alignedleft/tutorials/d3/setup/

04. 要素の追加

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
    d3.select("body").append("p").text("新しいパラグラフ!");
</script>
</body>
</html>

結果

新しいパラグラフ!

05. メソッドのチェイン

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
    d3.select("body")
        .append("p")
        .text("新しいパラグラフ!");
</script>
</body>
</html>

結果

新しいパラグラフ!

06 データのバインディング

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
    var dataset = [ 5, 10, 15, 20, 25 ];
    d3.select("body").selectAll("p")
        .data(dataset)
        .enter()
        .append("p")
        .text("新しいパラグラフ!");
 </script>
</body>
</html>

結果

新しいパラグラフ!

新しいパラグラフ!

新しいパラグラフ!

新しいパラグラフ!

新しいパラグラフ!

07. データの使い方

Chapter07
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
    var dataset = [ 5, 10, 15, 20, 25 ];
    d3.select("body").selectAll("p")
       .data(dataset)
       .enter()
       .append("p")
       .text(function(d) { return d; })
       .style("color", function(d) {
           if (d > 15) {   // 15 が区切り
              return "red";
           } else {
              return "black";
           }
        });
       console.log(d3.select("body").selectAll("p"));
</script>
</body>
</html>

結果

Kobito.zTbqkC.png

08 DIV 要素の描画

Chapter08
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--
div.bar {
   display: inline-block;
   width: 20px;
   height: 75px;   /* この数値は実行時に上書きされます */
   background-color: teal;
   margin-right: 2px;
}
-->
</style>
</head>

<body>
<script type="text/javascript">
    var dataset = [ 5, 10, 15, 20, 25 ];
    d3.select("body").selectAll("div")
       .data(dataset)
       .enter()
       .append("div")
       .attr("class", "bar")
       .style("height", function(d) {
           var barHeight = d * 5;  // 高さを 5 倍にします
           return barHeight + "px";
       });;
</script>
</body>
</html>

結果

Chapter09

09 data() の力

Chapter09
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--
div.bar {
   display: inline-block;
   width: 20px;
   height: 75px;   /* この数値は実行時に上書きされます */
   background-color: teal;
   margin-right: 2px;
}
-->
</style>
</head>

<body>
<script type="text/javascript">

    /*
     * 0~30のランダムな整数を生成。繰り返しは25回
     * 生成した数を配列に追加
     */
    var dataset = [];  
    for (var i = 0; i < 25; i++) {
        var newNumber = Math.round(Math.random() * 30);
        dataset.push(newNumber);
    }

    d3.select("body").selectAll("div")
        .data(dataset)  // <-- 答えはここに潜んでいます
        .enter()
        .append("div")
        .attr("class", "bar")
        .style("height", function(d) {
            var barHeight = d * 5;
            return barHeight + "px";
    });
</script>
</body>
</html>

結果(リロードするたびに変わります)

結果9

10 SVG の基本

Chapter10
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script type="text/javascript" src="d3/d3.js"></script>
<!--script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script-->
<style type="text/css">
<!--

svg .pumpkin {
   fill: yellow;
   stroke: orange;
   stroke-width: 5;
}
-->
</style>
</head>

<body>
<script type="text/javascript">
</script>
<svg width="500" height="500">
    <rect x="0" y="0" width="500" height="50"/>
    <circle cx="250" cy="100" r="25"/>
    <ellipse cx="250" cy="175" rx="100" ry="25"/>
    <line x1="0" y1="200" x2="500" y2="250" stroke="black"/>
    <text x="250" y="300" font-family="sans-serif"
   font-size="25" fill="gray">javascript</text>
   <circle cx="25" cy="300" r="22" class="pumpkin"/>
   <rect x="0" y="0" width="30" height="30" fill="purple"/>
   <rect x="20" y="5" width="30" height="30" fill="blue"/>
   <rect x="40" y="10" width="30" height="30" fill="green"/>
   <rect x="60" y="15" width="30" height="30" fill="yellow"/>
   <rect x="80" y="20" width="30" height="30" fill="red"/>
   <circle cx="25" cy="350" r="20" fill="rgba(128, 0, 128, 1.0)"/>
   <circle cx="50" cy="350" r="20" fill="rgba(0, 0, 255, 0.75)"/>
   <circle cx="75" cy="350" r="20" fill="rgba(0, 255, 0, 0.5)"/>
   <circle cx="100" cy="350" r="20" fill="rgba(255, 255, 0, 0.25)"/>
   <circle cx="125" cy="350" r="20" fill="rgba(255, 0, 0, 0.1)"/>
   <circle cx="25" cy="400" r="20"
           fill="rgba(128, 0, 128, 0.75)"
           stroke="rgba(0, 255, 0, 0.25)" stroke-width="10"/>
   <circle cx="65" cy="400" r="20"
           fill="rgba(128, 0, 128, 0.75)"
           stroke="rgba(0, 255, 0, 0.25)" stroke-width="10"
           opacity="0.5"/>
   <circle cx="105" cy="400" r="20"
           fill="rgba(128, 0, 128, 0.75)"
           stroke="rgba(0, 255, 0, 0.25)" stroke-width="10"
           opacity="0.2"/>
</svg>
</body>
</html>

結果

Kobito.7NUmUF.png

11 SVG の描画

chapter11
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--
svg .pumpkin {
   fill: yellow;
   stroke: orange;
   stroke-width: 5;
}
-->
</style>
</head>

<body>
<script type="text/javascript">
    var dataset = [ 5, 10, 15, 20, 25 ];

    var w = 500;
    var h = 50;
    var svg = d3.select("body")
                .append("svg")
                .attr("width", w)   // <-- ここ
                .attr("height", h); // <-- ここにも

    var circles = svg.selectAll("circle")
                     .data(dataset)
                     .enter()
                     .append("circle");

    circles.attr("cx", function(d, i) {
        return (i * 50) + 25;
    })
    .attr("cy", h/2)
    .attr("r", function(d) {
        return d;
    })
    .attr("fill", "yellow")
    .attr("stroke", "orange")
    .attr("stroke-width", function(d) {
        return d/2;
    });
</script>
</body>
</html>

結果

結果

12 データ型

http://ja.d3js.info/alignedleft/tutorials/d3/data-types/
省略

13 棒グラフの作成

Chapter13
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--
svg .pumpkin {
   fill: yellow;
   stroke: orange;
   stroke-width: 5;
}
-->
</style>
</head>

<body>
<script type="text/javascript">
    var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
                      11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
    var w = 500;
    var h = 100;
    var barPadding = 1;  // <-- パディング棒の間の間隔を追加
    var svg = d3.select("body")
                .append("svg")
                .attr("width", w)
                .attr("height", h);

    svg.selectAll("rect")
        .data(dataset)
        .enter()
        .append("rect")
        .attr("width", w / dataset.length - barPadding)
        .attr("height", function(d) {
            return 4 * d;
        })
        .attr("x", function(d, i) {
            return i * (w / dataset.length);
        })
        .attr("y", function(d) {
            return h - 4 * d;  // SVG の高さからデータの値を引く
        })
        .attr("fill", function(d) {
            return "rgb(0, 0, " + (d * 10) + ")";
        });

    svg.selectAll("text")
       .data(dataset)
       .enter()
       .append("text")
       .text(function(d) {
           return d;
       })
       .attr("text-anchor", "middle")
       .attr("x", function(d, i) {
           return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2;
       })
       .attr("y", function(d) {
           return h - (d * 4) + 14;
       })
       .attr("font-family", "sans-serif")
       .attr("font-size", "11px")
       .attr("fill", "white");

</script>
</body>
</html>

結果

結果13

14. 散布図の作成

chapter14
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--

-->
</style>
</head>

<body>
<script type="text/javascript">
    var dataset =
        [
            [   5, 20],
            [ 480, 90],
            [ 250, 50],
            [ 100, 33],
            [ 330, 95],
            [ 410, 12],
            [ 475, 44],
            [  25, 67],
            [  85, 21],
            [ 220, 88]
        ];
    var w = 500;
    var h = 100;
    var barPadding = 1;  // <-- パディング棒の間の間隔を追加

    //Create SVG element
    var svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h);

    svg.selectAll("circle")
        .data(dataset)
        .enter()
        .append("circle")
        .attr("cx", function(d) {
            return d[0];
        })
        .attr("cy", function(d) {
            return d[1];
        })
        .attr("r", 5).attr("r", function(d) {
            return Math.sqrt(h - d[1]);
        });

    svg.selectAll("text")
        .data(dataset)
        .enter()
        .append("text")
        .text(function(d) {
            return d[0] + "," + d[1];
        })
        .attr("x", function(d) {
            return d[0];
        })
        .attr("y", function(d) {
            return d[1];
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "red");

</script>
</body>
</html>

結果

Kobito.Yg2sjU.png

15. スケール

Chapter15
<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--

-->
</style>
</head>

<body>
<script type="text/javascript">
    var dataset = [
                    [5, 20], [480, 90], [250, 50], [100, 33], [330, 95],
                    [410, 12], [475, 44], [25, 67], [85, 21], [220, 88], [600, 150]
                ];

    var w = 500;
    var h = 300;
    var padding = 20;

    //Create SVG element
    var svg = d3.select("body")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

    var xScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) {
                        return d[0];
                    })]).range([padding, w - 2 * padding]);
    var yScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) {
                         return d[1];
                     })]).range([h - padding, padding]);
    var rScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) {
                         return d[1];
                    })]).range([2, 5]);


    svg.selectAll("circle")
        .data(dataset)
        .enter()
        .append("circle")
        .attr("cx", function(d) {
            return xScale(d[0]);
        })
        .attr("cy", function(d) {
            return yScale(d[1]);
        })
        .attr("r", function(d) {
            return rScale(d[1]);
        });

    svg.selectAll("text")
        .data(dataset)
        .enter()
        .append("text")
        .text(function(d) {
            return d[0] + "," + d[1];
        })
        .attr("x", function(d) {
            return xScale(d[0]);
        })
        .attr("y", function(d) {
            return yScale(d[1]);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "red");

</script>
</body>
</html>

結果

結果15

16. 軸

<!DOCTYPE html>
<html lang="ja">
<meta charset="utf-8">
<head>
<title> study d3 </title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style type="text/css">
<!--
.axis path,
.axis line {
   fill: none;
   stroke: black;
   shape-rendering: crispEdges;
}

.axis text {
   font-family: sans-serif;
   font-size: 11px;
}
-->
</style>
</head>

<body>
<script type="text/javascript">
    var dataset = [];
    var numDataPoints = 50;
    var xRange = Math.random() * 1000;
    var yRange = Math.random() * 1000;
    for (var i = 0; i < numDataPoints; i++) {
       var newNumber1 = Math.round(Math.random() * xRange);
       var newNumber2 = Math.round(Math.random() * yRange);
       dataset.push([newNumber1, newNumber2]);
    }

    var w = 500;
    var h = 300;
    var padding = 30;

    //Create SVG element
    var svg = d3.select("body")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

    var xScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) {
                        return d[0];
                    })]).range([padding, w - 2 * padding]);
    var yScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) {
                         return d[1];
                     })]).range([h - padding, padding]);
    var rScale = d3.scale.linear()
                    .domain([0, d3.max(dataset, function(d) {
                         return d[1];
                    })]).range([2, 5]);

    var xAxis = d3.svg.axis().scale(xScale).orient("bottom").ticks(5);
    var yAxis = d3.svg.axis().scale(yScale).orient("left").ticks(5);

    svg.selectAll("circle")
        .data(dataset)
        .enter()
        .append("circle")
        .attr("cx", function(d) {
            return xScale(d[0]);
        })
        .attr("cy", function(d) {
            return yScale(d[1]);
        })
        .attr("r", function(d) {
            return rScale(d[1]);
        });

/*
    svg.selectAll("text")
        .data(dataset)
        .enter()
        .append("text")
        .text(function(d) {
            return d[0] + "," + d[1];
        })
        .attr("x", function(d) {
            return xScale(d[0]);
        })
        .attr("y", function(d) {
            return yScale(d[1]);
        })
        .attr("font-family", "sans-serif")
        .attr("font-size", "11px")
        .attr("fill", "red");
*/

    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + (h - padding) + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(" + padding + ",0)")
        .call(yAxis);
</script>
</body>
</html>

結果

Kobito.EixJ67.png

18
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
daikumatan
2002-2015: Fujixerox, Numerical simulation Engineer 2015-2016: NVIDIA Japan, BD Manager 2016-2020: Rescale Japan, Evangelist 2020-Present: XTREME-D, CTO

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
18
Help us understand the problem. What is going on with this article?